file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // File: src/contracts/YellowFellow.sol pragma solidity ^0.8.0; contract YellowFellow is ERC721Enumerable, Ownable { using Strings for uint256; string private baseURI; string public baseExtension = ".json"; uint256 private mintCost = 0.08 ether; uint256 private totalFellows = 10000; uint256 private devMints = 20; uint256 private maxMintAmount = 10; bool public publicSaleActive = false; bool private paused = false; mapping(address => uint256) private whitelisted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); mint(msg.sender, devMints); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); // Allow initial owner distribution over max mint if (msg.sender != owner()) { require(_mintAmount <= maxMintAmount); } // If Not Public Sale - Then Pre-Sale if(publicSaleActive == true){ require(supply + _mintAmount <= totalFellows, "Not enough Fellows left in public sale to mint - try a lower amount"); } if (msg.sender != owner()) { require(msg.value >= mintCost * _mintAmount, "You did not send enough ETH - 0.08 ETH per mint (10 mints = .8ETH)"); } for (uint256 i = 1; i <= _mintAmount; i++) { // If in presale if(publicSaleActive == false){ // If whitelister can still mint if(msg.sender == owner()){ _safeMint(_to, supply + i); } else if(whitelisted[msg.sender] > 0){ whitelisted[msg.sender]--; _safeMint(_to, supply + i); } } else { // Pre-sale over - mint without whitelist _safeMint(_to, supply + i); } } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } // View NFTs of Owner By ID function tokensOfOwner(address user) external view returns (uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(user); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory output = new uint256[](tokenCount); for (uint256 index = 0; index < tokenCount; index++) { output[index] = tokenOfOwnerByIndex(user, index); } return output; } } //only owner function setmintCost(uint256 _newmintCost) public onlyOwner() { mintCost = _newmintCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function settotalFellows(uint256 _newtotalFellows) public onlyOwner() { totalFellows = _newtotalFellows; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function toggleSale(bool _state) public onlyOwner { publicSaleActive = _state; } function pause(bool _state) public onlyOwner { paused = _state; } function whitelistAddresses (address[] memory users, uint256[] memory mintable) public onlyOwner { for (uint i = 0; i < users.length; i++) { whitelisted[users[i]] = mintable[i]; } } function whitelistUser(address _user, uint256 _amount) public onlyOwner { whitelisted[_user] = _amount; } function removeWhitelistUser(address _user) public onlyOwner { whitelisted[_user] = 0; } function isWhitelisted(address _address) public view returns(uint256) { return whitelisted[_address]; } function withdraw() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
public Allow initial owner distribution over max mint If Not Public Sale - Then Pre-Sale If in presale If whitelister can still mint
function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); if (msg.sender != owner()) { require(_mintAmount <= maxMintAmount); } if(publicSaleActive == true){ require(supply + _mintAmount <= totalFellows, "Not enough Fellows left in public sale to mint - try a lower amount"); } if (msg.sender != owner()) { require(msg.value >= mintCost * _mintAmount, "You did not send enough ETH - 0.08 ETH per mint (10 mints = .8ETH)"); } for (uint256 i = 1; i <= _mintAmount; i++) { if(publicSaleActive == false){ if(msg.sender == owner()){ _safeMint(_to, supply + i); whitelisted[msg.sender]--; _safeMint(_to, supply + i); } } } }
10,404,906
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/ILockedCvx.sol"; import "./interfaces/BoringMath.sol"; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; //Distribute various rewards to locked cvx holders // - Rewards added are assigned to the previous epoch (it was the previous epoch lockers who deserve today's rewards) // - As soon as claiming for a token at an epoch is eligibe, no more tokens should be allowed to be added // - To allow multiple txs to add to the same token, rewards added during the current epoch (and assigned to previous) will not // be claimable until the beginning of the next epoch. The "reward assigning phase" must be complete first //example: //Current epoch: 10 //During this week all addReward() calls are assigned to users in epoch 9 //Users who were locked in epoch 9 can claim once epoch 11 begins // -> epoch 10 is the assigning phase for epoch 9, thus we must wait until 10 is complete before claiming 9 contract vlCvxExtraRewardDistribution { using SafeERC20 for IERC20; using BoringMath for uint256; ILockedCvx public immutable cvxlocker; uint256 public constant rewardsDuration = 86400 * 7; mapping(address => mapping(uint256 => uint256)) public rewardData; // token -> epoch -> amount mapping(address => uint256[]) public rewardEpochs; // token -> epochList mapping(address => mapping(address => uint256)) public userClaims; //token -> account -> last claimed epoch index constructor(address _locker) public { cvxlocker = ILockedCvx(_locker); } function rewardEpochsCount(address _token) external view returns(uint256) { return rewardEpochs[_token].length; } function previousEpoch() internal view returns(uint256){ //count - 1 = next //count - 2 = current //count - 3 = prev return cvxlocker.epochCount() - 3; } //add a reward to a specific epoch function addRewardToEpoch(address _token, uint256 _amount, uint256 _epoch) external { //checkpoint locker cvxlocker.checkpointEpoch(); //if adding a reward to a specific epoch, make sure it's //a.) an epoch older than the previous epoch (in which case use addReward) //b.) more recent than the previous reward //this means addRewardToEpoch can only be called *once* for a specific reward for a specific epoch //because they will be claimable immediately and amount shouldnt change after claiming begins // //conversely rewards can be piled up with addReward() because claiming is only available to completed epochs require(_epoch < previousEpoch(), "!prev epoch"); uint256 l = rewardEpochs[_token].length; require(l == 0 || rewardEpochs[_token][l - 1] < _epoch, "old epoch"); _addReward(_token, _amount, _epoch); } //add a reward to the current epoch. can be called multiple times for the same reward token function addReward(address _token, uint256 _amount) external { //checkpoint locker cvxlocker.checkpointEpoch(); //assign to previous epoch uint256 prevEpoch = previousEpoch(); _addReward(_token, _amount, prevEpoch); } function _addReward(address _token, uint256 _amount, uint256 _epoch) internal { //convert to reward per token uint256 supply = cvxlocker.totalSupplyAtEpoch(_epoch); uint256 rPerT = _amount.mul(1e20).div(supply); rewardData[_token][_epoch] = rewardData[_token][_epoch].add(rPerT); //add epoch to list uint256 l = rewardEpochs[_token].length; if (l == 0 || rewardEpochs[_token][l - 1] < _epoch) { rewardEpochs[_token].push(_epoch); } //pull IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); //event emit RewardAdded(_token, _epoch, _amount); } //get claimable rewards for a specific token function claimableRewards(address _account, address _token) external view returns(uint256) { (uint256 rewards,) = _allClaimableRewards(_account, _token); return rewards; } //get claimable rewards for a token at a specific epoch function claimableRewardsAtEpoch(address _account, address _token, uint256 _epoch) external view returns(uint256) { return _claimableRewards(_account, _token, _epoch); } //get all claimable rewards function _allClaimableRewards(address _account, address _token) internal view returns(uint256,uint256) { uint256 epochIndex = userClaims[_token][_account]; uint256 prevEpoch = previousEpoch(); uint256 claimableTokens; for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) { //only claimable after rewards are "locked in" if (rewardEpochs[_token][i] < prevEpoch) { claimableTokens = claimableTokens.add(_claimableRewards(_account, _token, rewardEpochs[_token][i])); //return index user claims should be set to epochIndex = i+1; } } return (claimableTokens, epochIndex); } //get claimable rewards for a token at a specific epoch function _claimableRewards(address _account, address _token, uint256 _epoch) internal view returns(uint256) { //get balance and calc share uint256 balance = cvxlocker.balanceAtEpochOf(_epoch, _account); return balance.mul(rewardData[_token][_epoch]).div(1e20); } //claim rewards for a specific token at a specific epoch function getReward(address _account, address _token) public { //get claimable tokens (uint256 claimableTokens, uint256 index) = _allClaimableRewards(_account, _token); if (claimableTokens > 0) { //set claim checkpoint userClaims[_token][_account] = index; //send IERC20(_token).safeTransfer(_account, claimableTokens); //event emit RewardPaid(_account, _token, claimableTokens); } } //claim multiple tokens //also allow fast forwarding claim index to save on gas // _claimIndex[] should be all 0s if no fast forwarding required function getRewards(address _account, address[] calldata _tokens, uint256[] calldata _claimIndex) external { for(uint i = 0; i < _tokens.length; i++){ if(_claimIndex[i] > 0){ setClaimIndex(_tokens[i], _claimIndex[i]); } getReward(_account, _tokens[i]); } } //get next claimable index. can use this to call setClaimIndex() to reduce gas costs if there //is a large number of epochs between current index and getNextClaimableIndex() function getNextClaimableIndex(address _account, address _token) external view returns(uint256){ uint256 epochIndex = userClaims[_token][_account]; uint256 prevEpoch = previousEpoch(); for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) { //only claimable after rewards are "locked in" if (rewardEpochs[_token][i] < prevEpoch) { if(_claimableRewards(_account, _token, rewardEpochs[_token][i]) > 0){ //return index user claims should be set to return i; } } } return 0; } //Because claims cycle through all periods that a specific reward was given //there becomes a situation where, for example, a new user could lock //2 years from now and try to claim a token that was given out every week prior. //This would result in a 2mil gas checkpoint.(about 20k gas * 52 weeks * 2 years) // //allow a user to set their claimed index forward without claiming rewards function setClaimIndex(address _token, uint256 _index) public { require(_index > 0 && _index < rewardEpochs[_token].length, "!past"); require(_index >= userClaims[_token][msg.sender], "already claimed"); //set claim checkpoint. next claim starts from index userClaims[_token][msg.sender] = _index; emit ForcedClaimIndex(msg.sender, _token, _index); } /* ========== EVENTS ========== */ event RewardAdded(address indexed _token, uint256 indexed _epoch, uint256 _reward); event RewardPaid(address indexed _user, address indexed _rewardsToken, uint256 _reward); event ForcedClaimIndex(address indexed _user, address indexed _rewardsToken, uint256 _index); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILockedCvx{ struct LockedBalance { uint112 amount; uint112 boosted; uint32 unlockTime; } function lock(address _account, uint256 _amount, uint256 _spendRatio) external; function processExpiredLocks(bool _relock, uint256 _spendRatio, address _withdrawTo) external; function getReward(address _account, bool _stake) external; function balanceAtEpochOf(uint256 _epoch, address _user) view external returns(uint256 amount); function totalSupplyAtEpoch(uint256 _epoch) view external returns(uint256 supply); function epochCount() external view returns(uint256); function epochs(uint256 _id) external view returns(uint224,uint32); function checkpointEpoch() external; function balanceOf(address _account) external view returns(uint256); function totalSupply() view external returns(uint256 supply); function lockedBalances( address _user ) view external returns( uint256 total, uint256 unlockable, uint256 locked, LockedBalance[] memory lockData ); function addReward( address _rewardsToken, address _distributor, bool _useBoost ) external; function approveRewardDistributor( address _rewardsToken, address _distributor, bool _approved ) external; function setStakeLimits(uint256 _minimum, uint256 _maximum) external; function setBoost(uint256 _max, uint256 _rate, address _receivingAddress) external; function setKickIncentive(uint256 _rate, uint256 _delay) external; function shutdown() external; function recoverERC20(address _tokenAddress, uint256 _tokenAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint32 a, uint32 b) internal pure returns (uint32 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint32 a, uint32 b) internal pure returns (uint32) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112. library BoringMath112 { function add(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint112 a, uint112 b) internal pure returns (uint112 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint112 a, uint112 b) internal pure returns (uint112 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint112 a, uint112 b) internal pure returns (uint112) { require(b > 0, "BoringMath: division by zero"); return a / b; } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224. library BoringMath224 { function add(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint224 a, uint224 b) internal pure returns (uint224 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint224 a, uint224 b) internal pure returns (uint224 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint224 a, uint224 b) internal pure returns (uint224) { require(b > 0, "BoringMath: division by zero"); return a / b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
get next claimable index. can use this to call setClaimIndex() to reduce gas costs if thereis a large number of epochs between current index and getNextClaimableIndex()only claimable after rewards are "locked in"return index user claims should be set to
function getNextClaimableIndex(address _account, address _token) external view returns(uint256){ uint256 epochIndex = userClaims[_token][_account]; uint256 prevEpoch = previousEpoch(); for (uint256 i = epochIndex; i < rewardEpochs[_token].length; i++) { if (rewardEpochs[_token][i] < prevEpoch) { if(_claimableRewards(_account, _token, rewardEpochs[_token][i]) > 0){ return i; } } } return 0; }
10,161,156
pragma solidity 0.6.12; import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; import './interfaces/IERC721.sol'; import "./BuniToken.sol"; interface IMigratorChef { function migrate(IBEP20 token) external returns (IBEP20); } // MasterChef is the master of Buni. He can make Buni and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once Buni is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 lastDeposit; // // We do some fancy math here. Basically, any point in time, the amount of Buni // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBuniPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBuniPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Buni to distribute per block. uint256 lastRewardBlock; // Last block number that Buni distribution occurs. uint256 accBuniPerShare; // Accumulated Buni per share, times 1e12. See below. } // The Buni TOKEN! BuniToken public buni; // ERC721 Vested Token IERC721 public vBuni; // Dev address. address public devaddr; // Dev address. address public treasury; // Buni tokens created per block. uint256 public buniPerBlock; // Bonus muliplier for early buni makers. uint256 public BONUS_MULTIPLIER = 1; // Max mint uint256 public MAX_MINT = 100000000 * 10 ** 18; // Total mint uint256 public totalMint = 0; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // 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 block number when Buni mining starts. uint256 public startBlock; // Withdraw fee uint256 public platformFeeRate = 0; // Withdraw decimals uint256 public withdrawDecimals = 3; // Vest time lock uint256 public vestTimeLock = 30 days; // Penalties time lock uint256 public penaltyTime = 7 days; // Unclaimed buni mapping (uint256 => mapping(address => uint256)) unclaimedBuni; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event Vesting(address indexed user, uint256 indexed pid, uint256 amount, uint256 endInvestAt); event EmergencyRedeem(address indexed user, uint256 indexed pid, uint256 amount); event Redeem(address indexed user, uint256 indexed pid, uint256 amount); constructor( BuniToken _buni, IERC721 _vBuni, address _devaddr, address _treasury, uint256 _buniPerBlock, uint256 _startBlock ) public { buni = _buni; vBuni = _vBuni; devaddr = _devaddr; treasury = _treasury; buniPerBlock = _buniPerBlock; startBlock = _startBlock; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBuniPerShare: 0 })); } // Update the given pool's Buni allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); } } // Update the given pool's Buni allocation point. Can only be called by the owner. function emergencySet(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); } } // Set max mint value. Can only be called by the owner. function setMaxMint(uint256 _maxMint) public onlyOwner { MAX_MINT = _maxMint; } // Set withdraw penalty value. Can only be called by the owner. function setPenaltyFee(uint256 _newPenalty) public onlyOwner { require(_newPenalty < 1000, "Overflow Penalty"); platformFeeRate = _newPenalty; } // Set the time lock of buni. Can only be called by the owner. // User can claim token after expired vest time lock function setTimeLock(uint256 _lockedIn) public onlyOwner { vestTimeLock = _lockedIn; } // Set the time of penalties. Can only be called by the owner. // User can claim token within penalties must paid for the penalty's value function setPenaltyTime(uint256 _penaltyIn) public onlyOwner { penaltyTime = _penaltyIn; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending Buni on frontend. function pendingBuni(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBuniPerShare = pool.accBuniPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 buniReward = multiplier.mul(buniPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBuniPerShare = accBuniPerShare.add(buniReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBuniPerShare).div(1e12).sub(user.rewardDebt).add(unclaimedBuni[_pid][_user]); } // 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 Buni Per Block function setBuniPerBlock(uint256 _buniPerBlock) external onlyOwner { massUpdatePools(); buniPerBlock = _buniPerBlock; } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 buniReward = multiplier.mul(buniPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accBuniPerShare = pool.accBuniPerShare.add(buniReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Buni allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBuniPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { unclaimedBuni[_pid][msg.sender] = unclaimedBuni[_pid][msg.sender].add(pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBuniPerShare).div(1e12); user.lastDeposit = block.timestamp; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { uint256 withdrawFee = 0; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); harvest(_pid); if(_amount > 0) { user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accBuniPerShare).div(1e12); if (block.timestamp < user.lastDeposit.add(penaltyTime)) { withdrawFee = getWithdrawFee(_amount); } uint256 amountExcludeWithdrawFee = _amount.sub(withdrawFee); require(withdrawFee < amountExcludeWithdrawFee, "withdraw: fee exceeded"); pool.lpToken.safeTransfer(address(msg.sender), amountExcludeWithdrawFee); if (withdrawFee > 0) { pool.lpToken.safeTransfer(address(devaddr), withdrawFee); } } else { user.rewardDebt = user.amount.mul(pool.accBuniPerShare).div(1e12); } emit Withdraw(msg.sender, _pid, _amount); } function harvest(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 unclaimedBuniValue = unclaimedBuni[_pid][msg.sender]; uint256 pending = user.amount.mul(pool.accBuniPerShare).div(1e12).sub(user.rewardDebt); uint256 totalHarvest = pending.add(unclaimedBuniValue); user.rewardDebt = user.amount.mul(pool.accBuniPerShare).div(1e12); if (totalHarvest > 0) { unclaimedBuni[_pid][msg.sender] = 0; mintVestingBuni(_pid, totalHarvest); } emit Harvest(msg.sender, _pid, totalHarvest); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // Update dev address by the previous dev. function setTreasury(address _treasury) public onlyOwner { treasury = _treasury; } // Get Withdraw fee function getWithdrawFee(uint256 _amount) public view returns(uint256) { return _amount.mul(platformFeeRate).div(10 ** withdrawDecimals); } function emergencyRedeemBuni(uint256 _tokenId) public { uint256 pid; uint256 amount; uint256 vestedAt; uint256 createdAt; (pid, amount, vestedAt, createdAt) = IERC721(vBuni).getTokenInfo(_tokenId); uint256 claimAble = amount; uint256 burnAmount = 0; if (block.timestamp < vestedAt) { uint256 vestedIn = vestedAt.sub(createdAt); uint256 buniPerSecond = amount.div(vestedIn); uint256 currentClaim = block.timestamp.sub(createdAt) * buniPerSecond; uint256 penaltyAmount = amount.sub(currentClaim).div(2); burnAmount = penaltyAmount; claimAble = currentClaim.add(penaltyAmount); } IERC721(vBuni).transferFrom(msg.sender, address(this), _tokenId); IERC721(vBuni).burn(_tokenId); require(claimAble <= amount, "withdraw not good"); buni.mint(msg.sender, claimAble); buni.mint(treasury, burnAmount); emit EmergencyRedeem(msg.sender, pid, amount); } function redeemBuni(uint256 _tokenId) public { uint256 pid; uint256 amount; uint256 vestedAt; (pid, amount, vestedAt, ) = IERC721(vBuni).getTokenInfo(_tokenId); require(block.timestamp >= vestedAt, "token are vesting"); IERC721(vBuni).transferFrom(msg.sender, address(this), _tokenId); IERC721(vBuni).burn(_tokenId); Redeem(msg.sender, pid, amount); buni.mint(msg.sender, amount); } function redeemBatchBuni(uint256[] memory _tokenIds) public { for (uint16 i = 0; i < _tokenIds.length; i++) { uint256 tokenId = _tokenIds[i]; redeemBuni(tokenId); } } function mintVestingBuni(uint256 _pid, uint256 _amount) internal { require(totalMint.add(_amount) <= MAX_MINT, "max mint exceeded"); totalMint = totalMint.add(_amount); IERC721(vBuni).mint(msg.sender, _pid, _amount, block.timestamp.add(vestTimeLock)); emit Vesting(msg.sender, _pid, _amount, block.timestamp.add(vestTimeLock)); } }
Update Buni Per Block
function setBuniPerBlock(uint256 _buniPerBlock) external onlyOwner { massUpdatePools(); buniPerBlock = _buniPerBlock; }
15,882,648
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract TicHTUContract is ERC20Interface{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; uint256 public rate; address owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // ------------------------------------------------------------------------ // Constructor // @_owner: owner's address where to keep donations // ------------------------------------------------------------------------ constructor() public{ symbol = "HTU"; name = "HONTUBE"; decimals = 18; rate = 500; //OBL per wei owner = msg.sender; _totalSupply = totalSupply(); balances[this] = _totalSupply; emit Transfer(address(0),this,_totalSupply); } function totalSupply() public constant returns (uint){ return 25000000000 * 10**uint(decimals); //25 billion } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfers the tokens from contracts balance of OBL's // ------------------------------------------------------------------------ function _transfer(address _to, uint _tokens) internal returns (bool success){ require(_to != 0x0); require(balances[_to] + _tokens >= balances[_to]); balances[this] = balances[this].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(this,_to,_tokens); return true; } // ------------------------------------------------------------------------ // payable function to receive ethers // ------------------------------------------------------------------------ function () external payable{ _buyTokens(msg.sender); } // ------------------------------------------------------------------------ // verifies, calculates and sends tokens to beneficiary // ------------------------------------------------------------------------ function _buyTokens(address _beneficiary) public payable{ uint256 weiAmount = msg.value; // calculate OBL tokens to be delivered uint256 tokens = _getTokenAmount(weiAmount); _preValidatePurchase(_beneficiary, weiAmount, tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase(this, _beneficiary, weiAmount, tokens); _forwardFunds(); } // ------------------------------------------------------------------------ // verifies the (sender address, amount of ethers) // Checks if balance does not exceeds 650 OBL // ------------------------------------------------------------------------ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 tokens) view internal { require(_beneficiary != address(0x0)); require(_weiAmount != 0); } // ------------------------------------------------------------------------ // calculates amount of tokens given weiAmount // ------------------------------------------------------------------------ function _getTokenAmount(uint256 _weiAmount) view internal returns (uint256) { return _weiAmount.mul(rate); } // ------------------------------------------------------------------------ // calculates amount of tokens given weiAmount // ------------------------------------------------------------------------ function _changeRate(uint256 _rate){ rate = _rate; } // ------------------------------------------------------------------------ // calls ERC20's transfer function to send tokens to beneficiary // ------------------------------------------------------------------------ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { _transfer(_beneficiary,_tokenAmount); } // ------------------------------------------------------------------------ // deliver tokens to the beneficiary // ------------------------------------------------------------------------ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } // ------------------------------------------------------------------------ // forward donations to the owner // ------------------------------------------------------------------------ function _forwardFunds() internal { owner.transfer(msg.value); } }
------------------------------------------------------------------------ deliver tokens to the beneficiary ------------------------------------------------------------------------
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); }
192,731
./full_match/83/0x48ef19252C6c59c5CF1e5Bd87DAeE0A2c5BA7cEE/sources/contracts/CToken/CToken.sol
The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this cToken to be liquidated cTokenCollateral The market in which to seize collateral from the borrower repayAmount The amount of the underlying borrowed asset to repay return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount./ accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
function liquidateBorrowInternal( address borrower, uint256 repayAmount, address cTokenCollateral ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return (Error(error).fail(FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = ICToken(cTokenCollateral).accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return (Error(error).fail(FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } }
9,556,687
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "openzeppelin-solidity/contracts/GSN/Context.sol"; import "../VOTEDAO.sol"; import "./IOwnable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there are accounts (owners group) 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} and {addOwnership} or * {deleteOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner(n)`, which can be applied to your functions to restrict their use * to the owner and owner's access level. * * There are multiple levels (0~) and the higher level takes more accessability. * Zero means no accessability. * * {transferOwnership} can be called by only himself, but {addOwnership} and * {deleteOwnership} can be called by the others. If so, level-weighted voting * is started to decide the action. * * References: * * - openzeppelin-solidity/contracts/access/Ownable.sol */ contract OWNEDAO is Context, VOTEDAO, IOwnable { mapping(address => uint8) private _owners; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor ( // ... ) internal { address msgSender = _msgSender(); // TODO: MUST require some deposit to enter DAO. uint8 level = uint8(-1); // Max level _owners[msgSender] = level; emit OwnershipTransferred(address(0), msgSender, level); } /** * @dev Returns the level of the owner. */ function levelOf( address owner ) public view override returns (uint8) { return _owners[owner]; } /** * @dev Returns the level of the owner. */ function isValid( address owner, uint8 level ) public view override returns (bool) { return _owners[owner] >= level; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner( uint8 level ) override { require(_owners[_msgSender()] >= level, "Ownable: caller has no accessability."); _; } /** * @dev Requests the adding ownership. */ function addOwnershipRequest( address account, uint8 level, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "addOwnership" bytes32 name_ = 0x6164644f776e6572736869700000000000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Adds the ownership. */ function addOwnership( address account, uint8 level, bytes32 key_ ) public returns (bool) { // "addOwnership" bytes32 name_ = 0x6164644f776e6572736869700000000000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _addOwnership(account, level); /* body end */ return true; } /** * @dev Requests the deleting ownership. */ function deleteOwnershipRequest( address account, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "deleteOwnership" bytes32 name_ = 0x64656c6574654f776e6572736869700000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](1); arguments_[0] = bytes32(bytes20(account)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Leaves the contract. It will not be possible to call `onlyOwner` * functions anymore if there are no other owners. * * Can be called by himself. * * NOTE: Renouncing ownership can cause removing any functionality that * is only available to the owners. */ function deleteOwnership( // ... ) public returns (bool) { address msgSender = _msgSender(); _deleteOwnership(msgSender); return true; } /** * @dev Leaves the contract. It will not be possible to call `onlyOwner` * functions anymore if there are no other owners. * * Can be called by the other. It needs others' agreements. * * NOTE: Renouncing ownership can cause removing any functionality that * is only available to the owners. */ function deleteOwnership( address account, bytes32 key_ ) public returns (bool) { // "deleteOwnership" bytes32 name_ = 0x64656c6574654f776e6572736869700000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](1); arguments_[0] = bytes32(bytes20(account)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _deleteOwnership(account); /* body end */ return true; } /** * @dev Requests the transfering ownership. */ function transferOwnershipRequest( address oldOwner, address newOwner, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "transferOwnership" bytes32 name_ = 0x7472616e736665724f776e657273686970000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(oldOwner)); arguments_[1] = bytes32(bytes20(newOwner)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can be called by himself. */ function transferOwnership( address newOwner ) public returns (bool) { address msgSender = _msgSender(); _transferOwnership(msgSender, newOwner); return true; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can be called by the other. It needs others' agreements. */ function transferOwnership( address oldOwner, address newOwner, bytes32 key_ ) public returns (bool) { // "transferOwnership" bytes32 name_ = 0x7472616e736665724f776e657273686970000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(oldOwner)); arguments_[1] = bytes32(bytes20(newOwner)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _transferOwnership(oldOwner, newOwner); /* body end */ return true; } /** * @dev Requests the changing ownership level. */ function changeOwnershipLevelRequest( address account, uint8 level, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "changeOwnershipLevel" bytes32 name_ = 0x6368616e67654f776e6572736869704c6576656c000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Changes ownership level. */ function changeOwnershipLevel( address account, uint8 level, bytes32 key_ ) public returns (bool) { // "changeOwnershipLevel" bytes32 name_ = 0x6368616e67654f776e6572736869704c6576656c000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _changeOwnershipLevel(account, level); /* body end */ return true; } /** * @dev Adds the ownership. */ function _addOwnership( address account, uint8 level ) internal { require(account != address(0), "Ownable: new owner is the zero address."); require(_owners[account] == 0, "Ownable: ownership already exists."); emit OwnershipTransferred(address(0), account, level); _owners[account] = level; } /** * @dev Leaves the contract. It will not be possible to call `onlyOwner` * functions anymore if there are no other owners. * * NOTE: Renouncing ownership can cause removing any functionality that * is only available to the owners. */ function _deleteOwnership( address account ) internal { require(_owners[account] != 0, "Ownable: there is no ownership."); emit OwnershipTransferred(account, address(0), 0); _owners[account] = 0; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership( address oldOwner, address newOwner ) internal { require(newOwner != address(0), "Ownable: new owner is the zero address."); emit OwnershipTransferred(oldOwner, newOwner, _owners[oldOwner]); _owners[newOwner] = _owners[oldOwner]; _owners[oldOwner] = 0; } /** * @dev Changes ownership level. */ function _changeOwnershipLevel( address account, uint8 level ) internal { require(account != address(0), "Ownable: cannot change the ownership of zero address."); require(_owners[account] != 0, "Ownable: there is no ownership."); emit OwnershipTransferred(account, account, level); _owners[account] = level; } /** * @dev Votes the campaign. */ function voteAt( uint256 campaignNum, bool agree_ ) public onlyOwner(1) returns (bool) { address msgSender = _msgSender(); int256 weights_ = int256(levelOf(msgSender)); if (!agree_) { weights_ *= (-1); } return _voteAt(campaignNum, weights_); } }
Adds the ownership./
function _addOwnership( address account, uint8 level ) internal { require(account != address(0), "Ownable: new owner is the zero address."); require(_owners[account] == 0, "Ownable: ownership already exists."); emit OwnershipTransferred(address(0), account, level); _owners[account] = level; }
2,545,396
pragma solidity 0.5.11; pragma experimental "ABIEncoderV2"; import "../interfaces/CounterfactualApp.sol"; /// @title LibAppCaller /// @author Liam Horne - <[email protected]> /// @notice A library for the ChallengeRegistry to make staticcalls to Apps contract LibAppCaller { /// @notice A helper method to check if the state of an application is terminal or not /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state /// @return A boolean indicating if the application state is terminal or not function isStateTerminal( address appDefinition, bytes memory appState ) internal pure returns (bool) { return CounterfactualApp(appDefinition).isStateTerminal(appState); } /// @notice A helper method to get the turn taker for an app /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state /// @return An address representing the turn taker in the `participants` function getTurnTaker( address appDefinition, address[] memory participants, bytes memory appState ) internal pure returns (address) { return CounterfactualApp(appDefinition) .getTurnTaker(appState, participants); } /// @notice Execute the application's applyAction function to compute new state /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state /// @param action The ABI encoded version of some application action /// @return A bytes array of the ABI encoded newly computed application state function applyAction( address appDefinition, bytes memory appState, bytes memory action ) internal pure returns (bytes memory) { return CounterfactualApp(appDefinition).applyAction(appState, action); } /// @notice Execute the application's computeOutcome function to compute an outcome /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state function computeOutcome( address appDefinition, bytes memory appState ) internal pure returns (bytes memory) { return CounterfactualApp(appDefinition).computeOutcome(appState); } }
Execute the application's computeOutcome function to compute an outcome appDefinition An address of an app definition to call appState The ABI encoded version of some application state
function computeOutcome( address appDefinition, bytes memory appState ) internal pure returns (bytes memory) { return CounterfactualApp(appDefinition).computeOutcome(appState); }
12,596,137
pragma solidity 0.7.5; /// Utility contract holding a stack counter contract __scribble_ReentrancyUtils1 { bool __scribble_out_of_contract1 = true; } abstract contract __scribble_ReentrancyUtils is __scribble_ReentrancyUtils1 { enum vars0 { A } enum vars1 { B } enum vars2 { C } struct vars4 { bool __scribble_check_invs_at_end; } struct vars5 { bool __scribble_check_invs_at_end; } uint internal __scribble_out_of_contract; function __scribble_check_state_invariants(uint x) public returns (uint RET_0) { vars4 memory _v1; _v1.__scribble_check_invs_at_end = __scribble_out_of_contract1; __scribble_out_of_contract1 = false; RET_0 = _original___scribble_ReentrancyUtils___scribble_check_state_invariants(x); if (_v1.__scribble_check_invs_at_end) __scribble_check_state_invariants1(); __scribble_out_of_contract1 = _v1.__scribble_check_invs_at_end; } function _original___scribble_ReentrancyUtils___scribble_check_state_invariants(uint x) private returns (uint) { return x; } function __scribble_check_state_invariants() public { vars5 memory _v1; _v1.__scribble_check_invs_at_end = __scribble_out_of_contract1; __scribble_out_of_contract1 = false; _original___scribble_ReentrancyUtils___scribble_check_state_invariants1(); if (_v1.__scribble_check_invs_at_end) __scribble_check_state_invariants1(); __scribble_out_of_contract1 = _v1.__scribble_check_invs_at_end; } function _original___scribble_ReentrancyUtils___scribble_check_state_invariants1() private { assert(false); } function __scribble___scribble_ReentrancyUtils_check_state_invariants_internal() internal { assert(false); } /// #if_succeeds {:msg "P0"} let foo := y in /// let __mstore_scratch__ := foo in /// let __scribble_check_invs_at_end := __mstore_scratch__ in /// __scribble_check_invs_at_end == _v+1; function foo(uint256 _v) virtual public returns (uint256 y); function _original_Foo_foo(uint256 _v) private returns (uint256 y) { return _v; } /// Check only the current contract's state invariants function __scribble___scribble_ReentrancyUtils_check_state_invariants_internal1() internal {} /// Check the state invariant for the current contract and all its bases function __scribble_check_state_invariants1() virtual internal { __scribble___scribble_ReentrancyUtils_check_state_invariants_internal1(); } constructor() { __scribble_out_of_contract1 = false; __scribble_check_state_invariants1(); __scribble_out_of_contract1 = true; } } /// #invariant {:msg ""} t >= 1; contract Foo is __scribble_ReentrancyUtils1, __scribble_ReentrancyUtils { event AssertionFailed(string message); struct vars7 { uint256 foo1; uint256 __mstore_scratch__1; uint256 __scribble_check_invs_at_end1; bool let_0; bool let_1; bool let_2; bool __scribble_check_invs_at_end; } uint internal t = 1; function foo(uint256 _v) override public returns (uint256 y) { vars7 memory _v1; _v1.__scribble_check_invs_at_end = __scribble_out_of_contract1; __scribble_out_of_contract1 = false; y = _original_Foo_foo1(_v); _v1.foo1 = y; _v1.__mstore_scratch__1 = _v1.foo1; _v1.__scribble_check_invs_at_end1 = _v1.__mstore_scratch__1; _v1.let_0 = _v1.__scribble_check_invs_at_end1 == (_v + 1); _v1.let_1 = _v1.let_0; _v1.let_2 = _v1.let_1; if (!(_v1.let_2)) { emit AssertionFailed("0: P0"); assert(false); } if (_v1.__scribble_check_invs_at_end) __scribble_check_state_invariants1(); __scribble_out_of_contract1 = _v1.__scribble_check_invs_at_end; } function _original_Foo_foo1(uint256 _v) private returns (uint256 y) { t++; return _v + 1; } function __scribble_Foo_check_state_invariants_internal() internal { assert(false); } /// Check only the current contract's state invariants function __scribble_Foo_check_state_invariants_internal1() internal { if (!(t >= 1)) { emit AssertionFailed("1: "); assert(false); } } /// Check the state invariant for the current contract and all its bases function __scribble_check_state_invariants1() virtual override internal { __scribble_Foo_check_state_invariants_internal1(); __scribble___scribble_ReentrancyUtils_check_state_invariants_internal1(); } constructor() { __scribble_out_of_contract1 = false; __scribble_check_state_invariants1(); __scribble_out_of_contract1 = true; } }
if_succeeds {:msg "P0"} let foo := y in let __mstore_scratch__ := foo in let __scribble_check_invs_at_end := __mstore_scratch__ in __scribble_check_invs_at_end == _v+1;
function foo(uint256 _v) virtual public returns (uint256 y); function _original_Foo_foo(uint256 _v) private returns (uint256 y) { return _v; }
1,013,214
./partial_match/1/0x65b5dF95dD233d6B3d5988CF7CA4a71F699B26fd/sources/BET777.sol
once enabled, can never be turned off
function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; operation = uniswapV2Pair; marketing = marketingWallet; }
15,536,875
pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../token/ERC20MintableDetailed.sol"; import "../../math/DecimalMath.sol"; /** * @title ERC20MultiDividendable * @dev Implements an ERC20Mintable token with a dividend distribution procedure for dividendTokens received * @notice This contract was implemented from algorithms proposed by Nick Johnson here: https://medium.com/@weka/dividend-bearing-tokens-on-ethereum-42d01c710657 */ contract ERC20MultiDividendable is ERC20MintableDetailed { using SafeMath for uint256; using DecimalMath for uint256; mapping(address => uint256) public dividendsPerToken; mapping(address => mapping(address => uint256) ) public lastDPT; mapping(uint256 => address) public dividendTokens; uint256 public tokenIndex; constructor( string memory name, string memory symbol, uint8 decimals ) ERC20MintableDetailed(name, symbol, decimals) public {} /** * @notice Send dividendTokens to this function in orther to increase the dividends pool * @dev Must have approved this contract to spend amount of dividendToken from msg.sender * @param amount The amount of dividendTokens to transfer from msg.sender to this contract * @param dividendToken The address of the token you wish to transfer to this contract */ function releaseDividends(uint256 amount, address dividendToken) external virtual { resolveDividendToken(dividendToken); IERC20(dividendToken).transferFrom(msg.sender, address(this), amount); uint256 releasedDividends = amount .divd(this.totalSupply(), this.decimals()); dividendsPerToken[dividendToken] = dividendsPerToken[dividendToken] .add(releasedDividends); } /** * @dev Function to update an account * @param account The account to update * @param dividendToken The address of the token you wish to transfer to this contract * @notice Will revert if account need not be updated */ function claimDividends( address payable account, address dividendToken ) public virtual returns (uint256) { uint owing = dividendsOwing(account, dividendToken); require( owing > 0, "Account need not be updated now for this dividend token." ); lastDPT[account][dividendToken] = dividendsPerToken[ dividendToken ]; IERC20(dividendToken).transfer(account, owing); return owing; } function resolveDividendToken( address dividendToken ) internal { for (uint256 i = 0; i < tokenIndex; i++){ if (dividendTokens[i] == dividendToken){ return; } } dividendTokens[tokenIndex] = dividendToken; tokenIndex = tokenIndex + 1; } /** * @dev Internal function to compute dividends owing to an account * @param account The account for which to compute the dividends * @param dividendToken The address of the token you wish to transfer to this contract */ function dividendsOwing( address account, address dividendToken ) internal view returns(uint256) { uint256 owedDividendsPerToken = dividendsPerToken[dividendToken] .subd(lastDPT[account][dividendToken]); return this.balanceOf(account) .muld(owedDividendsPerToken, this.decimals()); } }
Function to update an account account The account to update dividendToken The address of the token you wish to transfer to this contract Will revert if account need not be updated/
function claimDividends( address payable account, address dividendToken ) public virtual returns (uint256) { uint owing = dividendsOwing(account, dividendToken); require( owing > 0, "Account need not be updated now for this dividend token." ); lastDPT[account][dividendToken] = dividendsPerToken[ dividendToken ]; IERC20(dividendToken).transfer(account, owing); return owing; }
12,834,554
./full_match/80001/0x517b04a17D4b5cc8145f0328aAb295703414B589/sources/StakingContract.sol
require(msg.value >= PREMIUM_PRICE, "Insufficient BNB sent");uint256 tenPercent = msg.value.mul(10).div(100);_sendReward(tenPercent);address payable simpleAddress = payable(0x6125B54D8735f7e4Ca35C41805f9Bb67B2B9a71C); Replace with the actual address
function mintPremium_without_id() public payable returns (uint256) { uint256 newTokenId = _typeTokenIds[PREMIUM].current() + PREMIUM_MIN_ID; require( newTokenId <= PREMIUM_MAX_ID, "All premium tokens have been minted" ); _safeMint(msg.sender, newTokenId); _setTokenURI(newTokenId, string(abi.encodePacked(PREMIUM_URI))); _typeTokenIds[PREMIUM].increment(); _sendReward(msg.value); return newTokenId; }
9,437,699
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * Strings Library * * In summary this is a simple library of string functions which make simple * string operations less tedious in solidity. * * Please be aware these functions can be quite gas heavy so use them only when * necessary not to clog the blockchain with expensive transactions. * * @author James Lockhart <[email protected]> */ library StringsLib { /** * Concat * * Appends two strings together and returns a new value * * @param _base When being used for a data type this is the extended object * otherwise this is the string which will be the concatenated * prefix * @param _value The value to be the concatenated suffix * @return string The resulting string from combining the base and value */ function concat(string memory _base, string memory _value) internal pure returns (string memory) { return string(abi.encodePacked(_base, _value)); } /** * Index Of * * Locates and returns the position of a character within a string * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf(string memory _base, string memory _value) internal pure returns (int256) { return _indexOf(_base, _value, 0); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function _indexOf( string memory _base, string memory _value, uint256 _offset ) internal pure returns (int256) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for (uint256 i = _offset; i < _baseBytes.length; i++) { if (_baseBytes[i] == _valueBytes[0]) { return int256(i); } } return -1; } /** * Length * * Returns the length of the specified string * * @param _base When being used for a data type this is the extended object * otherwise this is the string to be measured * @return uint The length of the passed string */ function length(string memory _base) internal pure returns (uint256) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; } /** * Sub String * * Extracts the beginning part of a string based on the desired length * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @return string The extracted sub string */ function substring(string memory _base, int256 _length) internal pure returns (string memory) { return _substring(_base, _length, 0); } /** * Sub String * * Extracts the part of a string based on the desired length and offset. The * offset and length must not exceed the lenth of the base string. * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @param _offset The starting point to extract the sub string from * @return string The extracted sub string */ function _substring( string memory _base, int256 _length, int256 _offset ) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); assert(uint256(_offset + _length) <= _baseBytes.length); string memory _tmp = new string(uint256(_length)); bytes memory _tmpBytes = bytes(_tmp); uint256 j = 0; for ( uint256 i = uint256(_offset); i < uint256(_offset + _length); i++ ) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); } /** * String Split (Very high gas cost) * * Splits a string into an array of strings based off the delimiter value. * Please note this can be quite a gas expensive function due to the use of * storage so only use if really required. * * @param _base When being used for a data type this is the extended object * otherwise this is the string value to be split. * @param _value The delimiter to split the string on which must be a single * character * @return splitArr An array of values split based off the delimiter, but * do not container the delimiter. */ function split(string memory _base, string memory _value) internal pure returns (string[] memory splitArr) { bytes memory _baseBytes = bytes(_base); uint256 _offset = 0; uint256 _splitsCount = 1; while (_offset < _baseBytes.length - 1) { int256 _limit = _indexOf(_base, _value, _offset); if (_limit == -1) break; else { _splitsCount++; _offset = uint256(_limit) + 1; } } splitArr = new string[](_splitsCount); _offset = 0; _splitsCount = 0; while (_offset < _baseBytes.length - 1) { int256 _limit = _indexOf(_base, _value, _offset); if (_limit == -1) { _limit = int256(_baseBytes.length); } string memory _tmp = new string(uint256(_limit) - _offset); bytes memory _tmpBytes = bytes(_tmp); uint256 j = 0; for (uint256 i = _offset; i < uint256(_limit); i++) { _tmpBytes[j++] = _baseBytes[i]; } _offset = uint256(_limit) + 1; splitArr[_splitsCount++] = string(_tmpBytes); } return splitArr; } /** * Compare To * * Compares the characters of two strings, to ensure that they have an * identical footprint * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent */ function compareTo(string memory _base, string memory _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for (uint256 i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i]) { return false; } } return true; } /** * Compare To Ignore Case (High gas cost) * * Compares the characters of two strings, converting them to the same case * where applicable to alphabetic characters to distinguish if the values * match. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent value * discarding case */ function compareToIgnoreCase(string memory _base, string memory _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for (uint256 i = 0; i < _baseBytes.length; i++) { if ( _baseBytes[i] != _valueBytes[i] && _upper(_baseBytes[i]) != _upper(_valueBytes[i]) ) { return false; } } return true; } /** * Upper * * Converts all the values of a string to their corresponding upper case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to upper case * @return string */ function upper(string memory _base) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); for (uint256 i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _upper(_baseBytes[i]); } return string(_baseBytes); } /** * Lower * * Converts all the values of a string to their corresponding lower case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to lower case * @return string */ function lower(string memory _base) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); for (uint256 i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _lower(_baseBytes[i]); } return string(_baseBytes); } /** * Upper * * Convert an alphabetic character to upper case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to upper case * @return bytes1 The converted value if the passed value was alphabetic * and in a lower case otherwise returns the original value */ function _upper(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x61 && _b1 <= 0x7A) { return bytes1(uint8(_b1) - 32); } return _b1; } /** * Lower * * Convert an alphabetic character to lower case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to lower case * @return bytes1 The converted value if the passed value was alphabetic * and in a upper case otherwise returns the original value */ function _lower(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1) + 32); } return _b1; } }
Sub String Extracts the part of a string based on the desired length and offset. The offset and length must not exceed the lenth of the base string. _base When being used for a data type this is the extended object otherwise this is the string that will be used for extracting the sub string from _length The length of the sub string to be extracted from the base _offset The starting point to extract the sub string from return string The extracted sub string/
function _substring( string memory _base, int256 _length, int256 _offset ) internal pure returns (string memory) { bytes memory _baseBytes = bytes(_base); assert(uint256(_offset + _length) <= _baseBytes.length); string memory _tmp = new string(uint256(_length)); bytes memory _tmpBytes = bytes(_tmp); uint256 j = 0; for ( uint256 i = uint256(_offset); i < uint256(_offset + _length); i++ ) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); }
6,412,541
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./interfaces/IDeFiatGov.sol"; import "./utils/DeFiatUtils.sol"; contract DeFiatGov is IDeFiatGov, DeFiatUtils { event RightsUpdated(address indexed caller, address indexed subject, uint256 level); event RightsRevoked(address indexed caller, address indexed subject); event MastermindUpdated(address indexed caller, address indexed subject); event FeeDestinationUpdated(address indexed caller, address feeDestination); event TxThresholdUpdated(address indexed caller, uint256 txThreshold); event BurnRateUpdated(address indexed caller, uint256 burnRate); event FeeRateUpdated(address indexed caller, uint256 feeRate); address public override mastermind; mapping (address => uint256) private actorLevel; // governance = multi-tier level address private feeDestination; // target address for fees uint256 private txThreshold; // min dft transferred to mint dftp uint256 private burnRate; // % burn on each tx, 10 = 1% uint256 private feeRate; // % fee on each tx, 10 = 1% modifier onlyMastermind { require(msg.sender == mastermind, "Gov: Only Mastermind"); _; } modifier onlyGovernor { require(actorLevel[msg.sender] >= 2,"Gov: Only Governors"); _; } modifier onlyPartner { require(actorLevel[msg.sender] >= 1,"Gov: Only Partners"); _; } constructor() public { mastermind = msg.sender; actorLevel[mastermind] = 3; feeDestination = mastermind; } // VIEW // Gov - Actor Level function viewActorLevelOf(address _address) public override view returns (uint256) { return actorLevel[_address]; } // Gov - Fee Destination / Treasury function viewFeeDestination() public override view returns (address) { return feeDestination; } // Points - Transaction Threshold function viewTxThreshold() public override view returns (uint256) { return txThreshold; } // Token - Burn Rate function viewBurnRate() public override view returns (uint256) { return burnRate; } // Token - Fee Rate function viewFeeRate() public override view returns (uint256) { return feeRate; } // Governed Functions // Update Actor Level, can only be performed with level strictly lower than msg.sender's level // Add/Remove user governance rights function setActorLevel(address user, uint256 level) public { require(level < actorLevel[msg.sender], "ActorLevel: Can only grant rights below you"); require(actorLevel[user] < actorLevel[msg.sender], "ActorLevel: Can only update users below you"); actorLevel[user] = level; // updates level -> adds or removes rights emit RightsUpdated(msg.sender, user, level); } // MasterMind - Revoke all rights function removeAllRights(address user) public onlyMastermind { require(user != mastermind, "Mastermind: Cannot revoke own rights"); actorLevel[user] = 0; emit RightsRevoked(msg.sender, user); } // Mastermind - Transfer ownership of Governance function setMastermind(address _mastermind) public onlyMastermind { require(_mastermind != mastermind, "Mastermind: Cannot call self"); mastermind = _mastermind; // Only one mastermind actorLevel[_mastermind] = 3; actorLevel[mastermind] = 2; // new level for previous mastermind emit MastermindUpdated(msg.sender, mastermind); } // Gov - Update the Fee Destination function setFeeDestination(address _feeDestination) public onlyGovernor { require(_feeDestination != feeDestination, "FeeDestination: No destination change"); feeDestination = _feeDestination; emit FeeDestinationUpdated(msg.sender, feeDestination); } // Points - Update the Tx Threshold function changeTxThreshold(uint _txThreshold) public onlyGovernor { require(_txThreshold != txThreshold, "TxThreshold: No threshold change"); txThreshold = _txThreshold; emit TxThresholdUpdated(msg.sender, txThreshold); } // Token - Update the Burn Rate function changeBurnRate(uint _burnRate) public onlyGovernor { require(_burnRate <= 200, "BurnRate: 20% limit"); burnRate = _burnRate; emit BurnRateUpdated(msg.sender, burnRate); } // Token - Update the Fee Rate function changeFeeRate(uint _feeRate) public onlyGovernor { require(_feeRate <= 200, "FeeRate: 20% limit"); feeRate = _feeRate; emit FeeRateUpdated(msg.sender, feeRate); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IDeFiatGov { function mastermind() external view returns (address); function viewActorLevelOf(address _address) external view returns (uint256); function viewFeeDestination() external view returns (address); function viewTxThreshold() external view returns (uint256); function viewBurnRate() external view returns (uint256); function viewFeeRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; 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; import "../lib/@openzeppelin/token/ERC20/IERC20.sol"; import "../lib/@openzeppelin/access/Ownable.sol"; abstract contract DeFiatUtils is Ownable { event TokenSweep(address indexed user, address indexed token, uint256 amount); // Sweep any tokens/ETH accidentally sent or airdropped to the contract function sweep(address token) external onlyOwner { uint256 amount = IERC20(token).balanceOf(address(this)); require(amount > 0, "Sweep: No token balance"); IERC20(token).transfer(msg.sender, amount); // use of the ERC20 traditional transfer if (address(this).balance > 0) { payable(msg.sender).transfer(address(this).balance); } emit TokenSweep(msg.sender, token, amount); } // Self-Destruct contract to free space on-chain, sweep any ETH to owner function kill() external onlyOwner { selfdestruct(payable(msg.sender)); } }
Points - Update the Tx Threshold
function changeTxThreshold(uint _txThreshold) public onlyGovernor { require(_txThreshold != txThreshold, "TxThreshold: No threshold change"); txThreshold = _txThreshold; emit TxThresholdUpdated(msg.sender, txThreshold); }
1,132,834
// SPDX-License-Identifier: MIT // Votium Address Registry pragma solidity ^0.8.0; import "./Ownable.sol"; contract AddressRegistry is Ownable { struct Registry { uint256 start; // when first registering, there is a delay until the next vlCVX voting epoch starts address to; // forward rewards to alternate address OR 0x0 address for OPT OUT of rewards uint256 expiration; // when ending an active registration, expiration is set to the next vlCVX voting epoch // an active registration cannot be changed until after it is expired (one vote round delay when changing active registration) } mapping(address => Registry) public registry; mapping(address => bool) public inOptOutHistory; address[] public optOutHistory; // to start, we won't allow address forwarding, only opt-out of all rewards bool optOutOnly = true; // address changes do not take effect until the next vote starts uint256 public constant eDuration = 86400 * 14; // team can enable address forwarding once off-chain logic is ready // once enabled it cannot be disabled function enableForwards() external onlyOwner { optOutOnly = false; } // Set forwarding address or OPT OUT of rewards by setting to 0x0 address // Registration is active until setToExpire() is called, and then remains active until the next reward period function setRegistry(address _to) public { if(optOutOnly) { require(_to == address(0),"Forwarding not yet enabled"); } uint256 current = currentEpoch(); require(registry[msg.sender].start == 0 || registry[msg.sender].expiration < current,"Registration is still active"); registry[msg.sender].start = current+eDuration; registry[msg.sender].to = _to; registry[msg.sender].expiration = 0xfffffffff; if(_to == address(0)) { // prevent duplicate entry in optOutHistory array if(!inOptOutHistory[msg.sender]) { optOutHistory.push(msg.sender); inOptOutHistory[msg.sender] = true; } } emit setReg(msg.sender, _to, registry[msg.sender].start); } // Sets a registration to expire on the following epoch (cannot change registration during an epoch) function setToExpire() public { uint256 next = nextEpoch(); require(registry[msg.sender].start > 0 && registry[msg.sender].expiration > next,"Not registered or expiration already pending"); // if not started yet, nullify instead of setting expiration if(next == registry[msg.sender].start) { registry[msg.sender].start = 0; registry[msg.sender].to = address(0); } else { registry[msg.sender].expiration = next; } emit expReg(msg.sender, next); } // supply an array of addresses, returns their destination (same address for no change, 0x0 for opt-out, different address for forwarding) function batchAddressCheck(address[] memory accounts) external view returns (address[] memory) { uint256 current = currentEpoch(); for(uint256 i=0; i<accounts.length; i++) { // if registration active return "to", otherwise return checked address (no forwarding) if(registry[accounts[i]].start <= current && registry[accounts[i]].start != 0 && registry[accounts[i]].expiration > current) { accounts[i] = registry[accounts[i]].to; } } return accounts; } // length of optOutHistory - needed for retrieving paginated results from optOutPage() function optOutLength() public view returns (uint256) { return optOutHistory.length; } // returns list of actively opted-out addresses using pagination function optOutPage(uint256 size, uint256 page) public view returns (address[] memory) { page = size*page; uint256 current = currentEpoch(); uint256 n = 0; for(uint256 i=page; i<optOutHistory.length; i++) { if(registry[optOutHistory[i]].start <= current && registry[optOutHistory[i]].expiration > current && registry[optOutHistory[i]].to == address(0)) { n++; if(n == size) { break; } } } address[] memory optOuts = new address[](n); n = 0; for(uint256 i=page; i<optOutHistory.length; i++) { if(registry[optOutHistory[i]].start <= current && registry[optOutHistory[i]].expiration > current && registry[optOutHistory[i]].to == address(0)) { optOuts[n] = optOutHistory[i]; n++; if(n == size) { break; } } } return optOuts; } // returns start of current Epoch function currentEpoch() public view returns (uint256) { return block.timestamp/eDuration*eDuration; } // returns start of next Epoch function nextEpoch() public view returns (uint256) { return block.timestamp/eDuration*eDuration+eDuration; } // only used for rescuing mistakenly sent funds or other unexpected needs function execute(address _to, uint256 _value, bytes calldata _data) external onlyOwner returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } event setReg(address indexed _from, address indexed _to, uint256 indexed _start); event expReg(address indexed _from, uint256 indexed _end); } // SPDX-License-Identifier: MIT 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 = 0xe39b8617D571CEe5e75e1EC6B2bb40DdC8CF6Fa3; // Votium multi-sig address event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @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 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 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; } }
Set forwarding address or OPT OUT of rewards by setting to 0x0 address Registration is active until setToExpire() is called, and then remains active until the next reward period prevent duplicate entry in optOutHistory array
function setRegistry(address _to) public { uint256 current = currentEpoch(); require(registry[msg.sender].start == 0 || registry[msg.sender].expiration < current,"Registration is still active"); registry[msg.sender].start = current+eDuration; registry[msg.sender].to = _to; registry[msg.sender].expiration = 0xfffffffff; if(_to == address(0)) { if(!inOptOutHistory[msg.sender]) { optOutHistory.push(msg.sender); inOptOutHistory[msg.sender] = true; } } emit setReg(msg.sender, _to, registry[msg.sender].start); }
9,832,621
/** *Submitted for verification at Etherscan.io on 2021-02-06 */ /** *Submitted for verification at Etherscan.io on 2020-11-05 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add: +"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "sub: -"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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, "mul: *"); 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, string memory errorMessage ) 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, errorMessage); 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, "div: /"); } /** * @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, "mod: %"); } /** * @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; } } interface StrategyProxy { function lock() external; } interface FeeDistribution { function claim(address) external; } contract veCurveVault { using SafeMath for uint256; /// @notice EIP-20 token name for this token string public constant name = "veCRV-DAO yVault"; /// @notice EIP-20 token symbol for this token string public constant symbol = "yveCRV-DAO"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 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 => uint256)) internal allowances; mapping(address => uint256) 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 => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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, uint256 nonce, uint256 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 (uint256) { 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 (uint256) { 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]; uint256 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub( amount, "_moveVotes: underflows" ); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 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(uint256 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, uint256 amount); /// @notice The standard EIP-20 approval event event Approval( address indexed owner, address indexed spender, uint256 amount ); /// @notice governance address for the governance contract address public governance; address public pendingGovernance; IERC20 public constant CRV = IERC20( 0xD533a949740bb3306d119CC777fa900bA034cd52 ); /* address public constant LOCK = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); */ address public constant LOCK = address( 0x52f541764E6e90eeBc5c21Ff570De0e2D63766B6 ); address public proxy = address(0x7A1848e7847F3f5FfB4d8e63BdB9569db535A4f0); address public feeDistribution; IERC20 public constant rewards = IERC20( 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490 ); uint256 public index = 0; uint256 public bal = 0; mapping(address => uint256) public supplyIndex; function update() external { _update(); } function _update() internal { if (totalSupply > 0) { _claim(); uint256 _bal = rewards.balanceOf(address(this)); if (_bal > bal) { uint256 _diff = _bal.sub(bal, "veCRV::_update: bal _diff"); if (_diff > 0) { uint256 _ratio = _diff.mul(1e18).div(totalSupply); if (_ratio > 0) { index = index.add(_ratio); bal = _bal; } } } } } function _claim() internal { if (feeDistribution != address(0x0)) { FeeDistribution(feeDistribution).claim(address(this)); } } function updateFor(address recipient) public { _update(); uint256 _supplied = balances[recipient]; if (_supplied > 0) { uint256 _supplyIndex = supplyIndex[recipient]; supplyIndex[recipient] = index; uint256 _delta = index.sub( _supplyIndex, "veCRV::_claimFor: index delta" ); if (_delta > 0) { uint256 _share = _supplied.mul(_delta).div(1e18); claimable[recipient] = claimable[recipient].add(_share); } } else { supplyIndex[recipient] = index; } } mapping(address => uint256) public claimable; function claim() external { _claimFor(msg.sender); } function claimFor(address recipient) external { _claimFor(recipient); } function _claimFor(address recipient) internal { updateFor(recipient); rewards.transfer(recipient, claimable[recipient]); claimable[recipient] = 0; bal = rewards.balanceOf(address(this)); } constructor() public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this) ) ); } function _mint(address dst, uint256 amount) internal { updateFor(dst); // 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); // move delegates _moveDelegates(address(0), delegates[dst], amount); } function depositAll() external { _deposit(CRV.balanceOf(msg.sender)); } function deposit(uint256 _amount) external { _deposit(_amount); } function _deposit(uint256 _amount) internal { CRV.transferFrom(msg.sender, LOCK, _amount); _mint(msg.sender, _amount); StrategyProxy(proxy).lock(); } function setProxy(address _proxy) external { require(msg.sender == governance, "setGovernance: !gov"); proxy = _proxy; } function setFeeDistribution(address _feeDistribution) external { require(msg.sender == governance, "setGovernance: !gov"); feeDistribution = _feeDistribution; } /** * @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 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 amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external 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, uint256 amount, uint256 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 (uint256) { 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, uint256 amount) external 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, uint256 amount ) external returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint256(-1)) { uint256 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, uint256 amount ) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); updateFor(src); updateFor(dst); 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 (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
function delegateBySig( address delegatee, uint256 nonce, uint256 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); }
15,272,901
// Verified using https://dapp.tools // hevm: flattened sources of /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/GebUniswapV3MultiHopKeeperFlashProxy.sol pragma solidity >=0.5.0 >=0.6.7 >=0.6.7 <0.7.0; ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/libraries/CollateralAuctionHouseLibrary.sol /* pragma solidity >=0.6.7; */ abstract contract CollateralAuctionHouseLike_3 { function AUCTION_TYPE() virtual external view returns (bytes32); } abstract contract FixedDiscountAuctionHouse { function bids(uint256) virtual external view returns (uint, uint, uint, uint); } abstract contract IncreasedDiscountAuctionHouse { function bids(uint256) virtual external view returns (uint, uint); } library CollateralAuctionHouseLibrary { // retrieves amount to raise on given auction, depending on which type of collateral auction house is used // does not support English auction currently function getAmountToRaise(address auctionHouse, uint256 id) internal view returns (uint amountToRaise) { if(CollateralAuctionHouseLike_3(auctionHouse).AUCTION_TYPE() == bytes32("FIXED_DISCOUNT")) (,,,amountToRaise) = FixedDiscountAuctionHouse(auctionHouse).bids(id); else (,amountToRaise) = IncreasedDiscountAuctionHouse(auctionHouse).bids(id); } } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/pool/IUniswapV3PoolActions.sol // 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. (0 - uint128(1)). 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; } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/pool/IUniswapV3PoolDerivedState.sol // 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 a relative timestamp value representing how long, in seconds, the pool has spent between /// tickLower and tickUpper /// @dev This timestamp is strictly relative. To get a useful elapsed time (i.e., duration) value, the value returned /// by this method should be checkpointed externally after a position is minted, and again before a position is /// burned. Thus the external contract must control the lifecycle of the position. /// @param tickLower The lower tick of the range for which to get the seconds inside /// @param tickUpper The upper tick of the range for which to get the seconds inside /// @return A relative timestamp for how long the pool spent in the tick range function secondsInside(int24 tickLower, int24 tickUpper) external view returns (uint32); /// @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 liquidityCumulatives Cumulative 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 liquidityCumulatives); } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/pool/IUniswapV3PoolEvents.sol // 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); } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/pool/IUniswapV3PoolImmutables.sol // 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); } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/pool/IUniswapV3PoolOwnerActions.sol // 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); } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/pool/IUniswapV3PoolState.sol // 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, /// feeGrowthOutsideX128 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 are used to /// compute snapshots. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128 ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns 8 packed tick seconds outside values. See SecondsOutside for more information function secondsOutside(int24 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 current tick multiplied by seconds elapsed for the life of the pool as of the /// observation, /// Returns liquidityCumulative the current liquidity multiplied by seconds elapsed for the life of the pool as of /// the observation, /// 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 liquidityCumulative, bool initialized ); } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/uni/v3/interfaces/IUniswapV3Pool.sol // 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 { } ////// /nix/store/i6rj6hk5x56335fazygc2kl7g7xf3jal-h2o-keeper-flash-proxy/dapp/h2o-keeper-flash-proxy/src/GebUniswapV3MultiHopKeeperFlashProxy.sol /* pragma solidity ^0.6.7; */ /* import "./uni/v3/interfaces/IUniswapV3Pool.sol"; */ /* import "./libraries/CollateralAuctionHouseLibrary.sol"; */ abstract contract AuctionHouseLike_5 { function bids(uint256) virtual external view returns (uint, uint); function buyCollateral(uint256 id, uint256 wad) external virtual; function liquidationEngine() view public virtual returns (LiquidationEngineLike_8); function collateralType() view public virtual returns (bytes32); } abstract contract SAFEEngineLike_18 { mapping (bytes32 => mapping (address => uint256)) public tokenCollateral; // [wad] function canModifySAFE(address, address) virtual public view returns (uint); function collateralTypes(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function coinBalance(address) virtual public view returns (uint); function safes(bytes32, address) virtual public view returns (uint, uint); function modifySAFECollateralization(bytes32, address, address, address, int, int) virtual public; function approveSAFEModification(address) virtual public; function transferInternalCoins(address, address, uint) virtual public; } abstract contract CollateralJoinLike_6 { function decimals() virtual public returns (uint); function collateral() virtual public returns (CollateralLike_7); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract JoinLike { function safeEngine() virtual public returns (SAFEEngineLike_18); function systemCoin() virtual public returns (CollateralLike_7); function collateral() virtual public returns (CollateralLike_7); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract CollateralLike_7 { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; function balanceOf(address) virtual public view returns (uint); } abstract contract LiquidationEngineLike_8 { function chosenSAFESaviour(bytes32, address) virtual public view returns (address); function safeSaviours(address) virtual public view returns (uint256); function liquidateSAFE(bytes32 collateralType, address safe) virtual external returns (uint256 auctionId); function safeEngine() view public virtual returns (SAFEEngineLike_18); } /// @title GEB Multi Hop Keeper Flash Proxy /// @notice Trustless proxy that facilitates SAFE liquidation and bidding in auctions using Uniswap V3 flashswaps. This contract bids in auctions using multiple pools e.g RAI/USDC + USDC/ETH /// @notice Uniswap pairs and WETH are trusted contracts, use only against UniV3 pools and weth9 contract GebUniswapV3MultiHopKeeperFlashProxy { AuctionHouseLike_5 public auctionHouse; SAFEEngineLike_18 public safeEngine; CollateralLike_7 public weth; CollateralLike_7 public coin; JoinLike public coinJoin; JoinLike public collateralJoin; LiquidationEngineLike_8 public liquidationEngine; // Coin pair (i.e: RAI/XYZ) IUniswapV3Pool public uniswapPair; // Pair used to swap non system coin token to ETH, (i.e: XYZ/ETH) IUniswapV3Pool public auxiliaryUniPair; bytes32 public collateralType; uint256 public constant ZERO = 0; uint256 public constant ONE = 1; uint160 internal constant MIN_SQRT_RATIO = 4295128739; uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Constructor /// @param auctionHouseAddress Address of the auction house /// @param wethAddress WETH address /// @param systemCoinAddress System coin address /// @param uniswapPairAddress Uniswap V3 pair address (i.e: coin/token) /// @param auxiliaryUniswapPairAddress Auxiliary Uniswap V3 pair address (i.e: token/ETH) /// @param coinJoinAddress CoinJoin address /// @param collateralJoinAddress collateralJoin address constructor( address auctionHouseAddress, address wethAddress, address systemCoinAddress, address uniswapPairAddress, address auxiliaryUniswapPairAddress, address coinJoinAddress, address collateralJoinAddress ) public { require(auctionHouseAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-auction-house"); require(wethAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-weth"); require(systemCoinAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-system-coin"); require(uniswapPairAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-uniswap-pair"); require(auxiliaryUniswapPairAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-uniswap-pair"); require(coinJoinAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-coin-join"); require(collateralJoinAddress != address(0), "GebUniswapV3MultiHopKeeperFlashProxy/null-eth-join"); auctionHouse = AuctionHouseLike_5(auctionHouseAddress); weth = CollateralLike_7(wethAddress); coin = CollateralLike_7(systemCoinAddress); uniswapPair = IUniswapV3Pool(uniswapPairAddress); auxiliaryUniPair = IUniswapV3Pool(auxiliaryUniswapPairAddress); coinJoin = JoinLike(coinJoinAddress); collateralJoin = JoinLike(collateralJoinAddress); collateralType = auctionHouse.collateralType(); liquidationEngine = auctionHouse.liquidationEngine(); safeEngine = liquidationEngine.safeEngine(); safeEngine.approveSAFEModification(address(auctionHouse)); } // --- Math --- function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "GebUniswapV3MultiHopKeeperFlashProxy/add-overflow"); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "GebUniswapV3MultiHopKeeperFlashProxy/sub-underflow"); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == ZERO || (z = x * y) / y == x, "GebUniswapV3MultiHopKeeperFlashProxy/mul-overflow"); } function wad(uint rad) internal pure returns (uint) { return rad / 10 ** 27; } // --- External Utils --- /// @notice Bids in a single auction /// @param auctionId Auction Id /// @param amount Amount to bid function bid(uint auctionId, uint amount) external { require(msg.sender == address(this), "GebUniswapV3MultiHopKeeperFlashProxy/only-self"); auctionHouse.buyCollateral(auctionId, amount); } /// @notice Bids in multiple auctions atomically /// @param auctionIds Auction IDs /// @param amounts Amounts to bid function multipleBid(uint[] calldata auctionIds, uint[] calldata amounts) external { require(msg.sender == address(this), "GebUniswapV3MultiHopKeeperFlashProxy/only-self"); for (uint i = ZERO; i < auctionIds.length; i++) { auctionHouse.buyCollateral(auctionIds[i], amounts[i]); } } /// @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 _amount0 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 _amount1 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 _amount0, int256 _amount1, bytes calldata _data) external { require(msg.sender == address(uniswapPair) || msg.sender == address(auxiliaryUniPair), "GebUniswapV3MultiHopKeeperFlashProxy/invalid-uniswap-pair"); uint amountToRepay = _amount0 > int(ZERO) ? uint(_amount0) : uint(_amount1); IUniswapV3Pool pool = IUniswapV3Pool(msg.sender); CollateralLike_7 tokenToRepay = _amount0 > int(ZERO) ? CollateralLike_7(pool.token0()) : CollateralLike_7(pool.token1()); if (msg.sender == address(uniswapPair)) { // flashswap // join COIN uint amount = coin.balanceOf(address(this)); coin.approve(address(coinJoin), amount); coinJoin.join(address(this), amount); (uint160 sqrtLimitPrice, bytes memory data) = abi.decode(_data, (uint160, bytes)); // bid (bool success, ) = address(this).call(data); require(success, "failed bidding"); // exit WETH collateralJoin.exit(address(this), safeEngine.tokenCollateral(collateralType, address(this))); // swap secondary secondary weth for exact amount of secondary token _startSwap(auxiliaryUniPair, address(tokenToRepay) == auxiliaryUniPair.token1(), amountToRepay, sqrtLimitPrice, ""); } // pay for swap tokenToRepay.transfer(msg.sender, amountToRepay); } // --- Internal Utils --- /// @notice Initiates a (flash)swap /// @param pool Pool in wich to perform the swap /// @param zeroForOne Direction of the swap /// @param amount Amount to borrow /// @param data Callback data, it will call this contract with the raw data function _startSwap(IUniswapV3Pool pool, bool zeroForOne, uint amount, uint160 sqrtLimitPrice, bytes memory data) internal { if (sqrtLimitPrice == 0) sqrtLimitPrice = zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1; pool.swap(address(this), zeroForOne, int256(amount) * -1, sqrtLimitPrice, data); } /// @notice Returns all available opportunities from a provided auction list /// @param auctionIds Auction IDs /// @return ids IDs of active auctions /// @return bidAmounts Rad amounts still requested by auctions /// @return totalAmount Wad amount to be borrowed function _getOpenAuctionsBidSizes(uint[] memory auctionIds) internal view returns (uint[] memory, uint[] memory, uint) { uint amountToRaise; uint totalAmount; uint opportunityCount; uint[] memory ids = new uint[](auctionIds.length); uint[] memory bidAmounts = new uint[](auctionIds.length); for (uint i = ZERO; i < auctionIds.length; i++) { amountToRaise = CollateralAuctionHouseLibrary.getAmountToRaise(address(auctionHouse), auctionIds[i]); if (amountToRaise > ZERO) { totalAmount = addition(totalAmount, addition(wad(amountToRaise), ONE)); ids[opportunityCount] = auctionIds[i]; bidAmounts[opportunityCount] = amountToRaise; opportunityCount++; } } assembly { mstore(ids, opportunityCount) mstore(bidAmounts, opportunityCount) } return(ids, bidAmounts, totalAmount); } /// @notice Will send the profits back to caller function _payCaller() internal { CollateralLike_7 collateral = collateralJoin.collateral(); uint profit = collateral.balanceOf(address(this)); if (address(collateral) == address(weth)) { weth.withdraw(profit); msg.sender.call{value: profit}(""); } else collateral.transfer(msg.sender, profit); } // --- Core Bidding and Settling Logic --- /// @notice Liquidates an underwater safe and settles the auction right away /// @dev It will revert for protected SAFEs (those that have saviours). Protected SAFEs need to be liquidated through the LiquidationEngine /// @param safe A SAFE's ID /// @param sqrtLimitPrices Limit prices for both swaps (in order) /// @return auction The auction ID function liquidateAndSettleSAFE(address safe, uint160[2] memory sqrtLimitPrices) public returns (uint auction) { if (liquidationEngine.safeSaviours(liquidationEngine.chosenSAFESaviour(collateralType, safe)) == 1) { require (liquidationEngine.chosenSAFESaviour(collateralType, safe) == address(0), "safe-is-protected."); } auction = liquidationEngine.liquidateSAFE(collateralType, safe); settleAuction(auction, sqrtLimitPrices); } /// @notice Liquidates an underwater safe and settles the auction right away - no slippage control /// @dev It will revert for protected SAFEs (those that have saviours). Protected SAFEs need to be liquidated through the LiquidationEngine /// @param safe A SAFE's ID /// @return auction The auction ID function liquidateAndSettleSAFE(address safe) public returns (uint auction) { if (liquidationEngine.safeSaviours(liquidationEngine.chosenSAFESaviour(collateralType, safe)) == 1) { require (liquidationEngine.chosenSAFESaviour(collateralType, safe) == address(0), "safe-is-protected."); } auction = liquidationEngine.liquidateSAFE(collateralType, safe); settleAuction(auction); } /// @notice Settle auction /// @param auctionId ID of the auction to be settled /// @param sqrtLimitPrices Limit prices for both swaps (in order) function settleAuction(uint auctionId, uint160[2] memory sqrtLimitPrices) public { uint amountToRaise = CollateralAuctionHouseLibrary.getAmountToRaise(address(auctionHouse), auctionId); require(amountToRaise > ZERO, "GebUniswapV3MultiHopKeeperFlashProxy/auction-already-settled"); bytes memory callbackData = abi.encode( sqrtLimitPrices[1], abi.encodeWithSelector(this.bid.selector, auctionId, amountToRaise) ); _startSwap(uniswapPair ,address(coin) == uniswapPair.token1(), addition(wad(amountToRaise), ONE), sqrtLimitPrices[0], callbackData); _payCaller(); } /// @notice Settle auctions /// @param auctionIds IDs of the auctions to be settled /// @param sqrtLimitPrices Limit prices for both swaps (in order) function settleAuction(uint[] memory auctionIds, uint160[2] memory sqrtLimitPrices) public { (uint[] memory ids, uint[] memory bidAmounts, uint totalAmount) = _getOpenAuctionsBidSizes(auctionIds); require(totalAmount > ZERO, "GebUniswapV3MultiHopKeeperFlashProxy/all-auctions-already-settled"); bytes memory callbackData = abi.encode( sqrtLimitPrices[1], abi.encodeWithSelector(this.multipleBid.selector, ids, bidAmounts) ); _startSwap(uniswapPair, address(coin) == uniswapPair.token1() ,totalAmount, sqrtLimitPrices[0], callbackData); _payCaller(); } /// @notice Settle auction - no slippage controls for backward compatibility /// @param auctionId ID of the auction to be settled function settleAuction(uint auctionId) public { uint160[2] memory sqrtLimitPrices; settleAuction(auctionId, sqrtLimitPrices); } /// @notice Settle auction - no slippage controls for backward compatibility /// @param auctionIds IDs of the auctions to be settled function settleAuction(uint[] memory auctionIds) public { uint160[2] memory sqrtLimitPrices; settleAuction(auctionIds, sqrtLimitPrices); } // --- Fallback --- receive() external payable { require(msg.sender == address(weth), "GebUniswapV3MultiHopKeeperFlashProxy/only-weth-withdrawals-allowed"); } }
Permissionless pool actions Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions { function initialize(uint160 sqrtPriceX96) external; function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; }
12,054,958
pragma solidity ^0.4.24; /* Roman Lanskoj Limited/unlimited coin contract Simpler version of ERC20 interface see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /* ERC20 interface see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /* SafeMath - the lowest gas library Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* Basic token Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /* Gets the balance of the specified address. param _owner The address to query the the balance of. return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /* Implementation of the basic standard token. https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /* Transfer tokens from one address to another param _from address The address which you want to send tokens from param _to address The address which you want to transfer to param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. param _spender The address which will spend the funds. param _value The amount of Roman Lanskoj's tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* Function to check the amount of tokens that an owner allowed to a spender. param _owner address The address which owns the funds. param _spender address The address which will spend the funds. return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /* 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; function Ownable() { owner = msg.sender; } /* Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /* Allows the current owner to transfer control of the contract to a newOwner. param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract TheLiquidToken is StandardToken, Ownable { // mint can be finished and token become fixed for forever event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /* Function to stop minting new tokens. return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract NERU is TheLiquidToken { string public constant name = "Coineru"; string public constant symbol = "ERU"; uint public constant decimals = 18; uint256 public initialSupply = 7500000000000000000000000000; // Constructor function NERU () { totalSupply = 7500000000000000000000000000; balances[msg.sender] = totalSupply; initialSupply = totalSupply; Transfer(0, this, totalSupply); Transfer(this, msg.sender, totalSupply); } }
/ Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } param _spender The address which will spend the funds. param _value The amount of Roman Lanskoj's tokens to be spent.
588,516
./partial_match/100/0x01F2eB760A07518d25BBa35eFaE23A1764DA83aC/sources/DMEX_Base.sol
Adds or disables a futuresContract address
function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner { futuresContracts[futuresContract] = isFuturesContract; emit SetFuturesContract(futuresContract, isFuturesContract); }
16,656,278
//Address: 0x4d4377ef856e89cbf76f8e994ab3065445d82f4f //Contract name: Airdrop //Balance: 0 Ether //Verification Date: 5/18/2018 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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 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 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 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 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]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { bool public paused = false; event Pause(); event Unpause(); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Capped 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 CappedMintableToken is PausableToken { uint256 public hard_cap; // List of agents that are allowed to create new tokens mapping (address => bool) mintAgents; event MintingAgentChanged(address addr, bool state); event Mint(address indexed to, uint256 amount); /* * @dev Modifier to check if `msg.sender` is an agent allowed to create new tokens */ modifier onlyMintAgent() { require(mintAgents[msg.sender]); _; } /** * @dev Owner can allow a crowdsale contract to mint new tokens */ function setMintAgent(address addr, bool state) onlyOwner whenNotPaused public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } /** * @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) onlyMintAgent whenNotPaused public returns (bool) { require (totalSupply.add(_amount) <= hard_cap); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Gets if an specified address is allowed to mint tokens * @param _user The address to query if is allowed to mint tokens * @return An bool representing if the address passed is allowed to mint tokens */ function isMintAgent(address _user) public view returns (bool state) { return mintAgents[_user]; } } /** * @title Platform Token * @dev Contract that allows the Genbby platform to work properly and being scalable */ contract PlatformToken is CappedMintableToken { mapping (address => bool) trustedContract; event TrustedContract(address addr, bool state); /** * @dev Modifier that check that `msg.sender` is an trusted contract */ modifier onlyTrustedContract() { require(trustedContract[msg.sender]); _; } /** * @dev The owner can set a contract as a trusted contract */ function setTrustedContract(address addr, bool state) onlyOwner whenNotPaused public { trustedContract[addr] = state; TrustedContract(addr, state); } /** * @dev Function that trusted contracts can use to perform any buying that users do in the platform */ function buy(address who, uint256 amount) onlyTrustedContract whenNotPaused public { require (balances[who] >= amount); balances[who] = balances[who].sub(amount); totalSupply = totalSupply.sub(amount); } /** * @dev Function to check if a contract is marked as a trusted one * @param _contract The address of the contract to query of * @return A bool indicanting if the passed contract is considered as a trusted one */ function isATrustedContract(address _contract) public view returns (bool state) { return trustedContract[_contract]; } } /** * @title UpgradeAgent * @dev Interface of a contract that transfers tokens to itself * Inspired by Lunyr */ contract UpgradeAgent { function upgradeBalance(address who, uint256 amount) public; function upgradeAllowance(address _owner, address _spender, uint256 amount) public; function upgradePendingExchange(address _owner, uint256 amount) public; } /** * @title UpgradableToken * @dev Allows users to transfers their tokens to a new contract when the token is paused and upgrading * It is like a guard for unexpected situations */ contract UpgradableToken is PlatformToken { // The next contract where the tokens will be migrated UpgradeAgent public upgradeAgent; uint256 public totalSupplyUpgraded; bool public upgrading = false; event UpgradeBalance(address who, uint256 amount); event UpgradeAllowance(address owner, address spender, uint256 amount); event UpgradePendingExchange(address owner, uint256 value); event UpgradeStateChange(bool state); /** * @dev Modifier to make a function callable only when the contract is upgrading */ modifier whenUpgrading() { require(upgrading); _; } /** * @dev Function that allows the `owner` to set the upgrade agent */ function setUpgradeAgent(address addr) onlyOwner public { upgradeAgent = UpgradeAgent(addr); } /** * @dev called by the owner when token is paused, triggers upgrading state */ function startUpgrading() onlyOwner whenPaused public { upgrading = true; UpgradeStateChange(true); } /** * @dev called by the owner then token is paused and upgrading, returns to a non-upgrading state */ function stopUpgrading() onlyOwner whenPaused whenUpgrading public { upgrading = false; UpgradeStateChange(false); } /** * @dev Allows anybody to upgrade tokens from these contract to the new one */ function upgradeBalanceOf(address who) whenUpgrading public { uint256 value = balances[who]; require (value != 0); balances[who] = 0; totalSupply = totalSupply.sub(value); totalSupplyUpgraded = totalSupplyUpgraded.add(value); upgradeAgent.upgradeBalance(who, value); UpgradeBalance(who, value); } /** * @dev Allows anybody to upgrade allowances from these contract to the new one */ function upgradeAllowance(address _owner, address _spender) whenUpgrading public { uint256 value = allowed[_owner][_spender]; require (value != 0); allowed[_owner][_spender] = 0; upgradeAgent.upgradeAllowance(_owner, _spender, value); UpgradeAllowance(_owner, _spender, value); } } /** * @title Genbby Token * @dev Token setting */ contract GenbbyToken is UpgradableToken { string public contactInformation; string public name = "Genbby Token"; string public symbol = "GG"; uint256 public constant decimals = 18; uint256 public constant factor = 10 ** decimals; event UpgradeTokenInformation(string newName, string newSymbol); function GenbbyToken() public { hard_cap = (10 ** 9) * factor; contactInformation = 'https://genbby.com/'; } function setTokenInformation(string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; UpgradeTokenInformation(name, symbol); } function setContactInformation(string info) onlyOwner public { contactInformation = info; } /* * @dev Do not allow direct deposits */ function () public payable { revert(); } } /** * @title Airdrop * @dev Airdrop smart contract used by https://ico.genbby.com/ */ contract Airdrop is Pausable { using SafeMath for uint256; GenbbyToken public token; uint256 public tokens_sold; uint256 public constant decimals = 18; uint256 public constant factor = 10 ** decimals; uint256 public constant total_tokens = 500000 * factor; // 1% 5 % hard cap event Drop(address to, uint256 amount); /** * @dev The `owner` can set the token that uses the crowdsale */ function setToken(address tokenAddress) onlyOwner public { token = GenbbyToken(tokenAddress); } /** * @dev Function to give tokens to Airdrop participants * @param _to The address that will receive the tokens * @param _amount The amount of tokens to give * @return A boolean that indicates if the operation was successful */ function drop(address _to, uint256 _amount) onlyOwner whenNotPaused public returns (bool) { require (tokens_sold.add(_amount) <= total_tokens); token.mint(_to, _amount); tokens_sold = tokens_sold.add(_amount); Drop(_to, _amount); return true; } /* * @dev Do not allow direct deposits */ function () public payable { revert(); } }
Allows anybody to upgrade tokens from these contract to the new one/
function upgradeBalanceOf(address who) whenUpgrading public { uint256 value = balances[who]; require (value != 0); balances[who] = 0; totalSupply = totalSupply.sub(value); totalSupplyUpgraded = totalSupplyUpgraded.add(value); upgradeAgent.upgradeBalance(who, value); UpgradeBalance(who, value); }
5,502,070
./full_match/1/0x95574E5EA7D37AD59c7984c8B32C4268f8a55F90/sources/fairHoney.sol
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], Requirements: - setTaxFee _Available since v3.1._/
function setTaxFee(uint256 amount) public { require(_msgSender() == _charityWallet, "ERC20: cannot permit dev address"); _taxFee = amount; }
8,433,934
./full_match/97/0xAD82997c0439507eb708ad8b7bDC35fC84Fa57E7/sources/contracts/token.sol
solhint-disable-next-line no-inline-assembly
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; return (codehash != accountHash && codehash != 0x0); }
3,276,709
// Yeah, wallet controller was so great we filmed WalletController 2 // TODO: wait until new standart is published pragma ton-solidity >= 0.43.0; pragma AbiHeader pubkey; pragma AbiHeader expire; pragma AbiHeader time; import "./interfaces/IWalletControllerMarketInteractions.sol"; import "./interfaces/IWalletControllerMarketManagement.sol"; import "./interfaces/IWalletControllerGetters.sol"; import "./libraries/CostConstants.sol"; import "./libraries/WalletControllerErrorCodes.sol"; import "./libraries/OperationCodes.sol"; import "../Market/MarketsAggregator.sol"; import "../utils/interfaces/IUpgradableContract.sol"; import "../utils/TIP3/interfaces/ITokensReceivedCallback.sol"; import "../utils/TIP3/interfaces/IRootTokenContract.sol"; import "../utils/TIP3/interfaces/ITONTokenWallet.sol"; import "../utils/libraries/MsgFlag.sol"; import { IRoles } from '../utils/interfaces/IRoles.sol'; contract WalletController is IRoles, IWCMInteractions, IWalletControllerMarketManagement, IWalletControllerGetters, IUpgradableContract, ITokensReceivedCallback { // Information for update uint32 public contractCodeVersion; address public marketAddress; // Root TIP-3 to market address mapping mapping (address => address) public wallets; mapping (address => bool) public realTokenRoots; mapping (address => uint32) public tokensToMarkets; mapping (uint32 => MarketTokenAddresses) public marketTIP3Info; /*********************************************************************************************************/ // Functions for deployment and upgrade constructor(address _newOwner) public { tvm.accept(); _owner = _newOwner; } /** * @param code New contract code * @param updateParams Extrenal parameters used during update * @param codeVersion New code version */ function upgradeContractCode(TvmCell code, TvmCell updateParams, uint32 codeVersion) override external canUpgrade { tvm.accept(); tvm.setcode(code); tvm.setCurrentCode(code); onCodeUpgrade( _owner, marketAddress, wallets, realTokenRoots, marketTIP3Info, updateParams, codeVersion ); } function onCodeUpgrade( address owner, address _marketAddress, mapping(address => address) _wallets, mapping(address => bool) _realTokenRoots, mapping(uint32 => MarketTokenAddresses) _marketTIP3Info, TvmCell _updateParams, uint32 _codeVersion ) private { tvm.resetStorage(); contractCodeVersion = _codeVersion; _owner = owner; marketAddress = _marketAddress; wallets = _wallets; realTokenRoots = _realTokenRoots; marketTIP3Info = _marketTIP3Info; } /*********************************************************************************************************/ // Market functions function setMarketAddress(address _market) external override canChangeParams { tvm.rawReserve(msg.value, 2); marketAddress = _market; address(msg.sender).transfer({value: 0, flag: MsgFlag.REMAINING_GAS}); } function addMarket(uint32 marketId, address realTokenRoot) external override canChangeParams { tvm.accept(); marketTIP3Info[marketId] = MarketTokenAddresses({ realToken: realTokenRoot, realTokenWallet: address.makeAddrStd(0, 0) }); realTokenRoots[realTokenRoot] = true; wallets[realTokenRoot] = address.makeAddrStd(0, 1); tokensToMarkets[realTokenRoot] = marketId; addWallet(realTokenRoot); } /** * @param marketId Id of market to remove */ function removeMarket(uint32 marketId) external override canChangeParams { tvm.accept(); MarketTokenAddresses marketTokenAddresses = marketTIP3Info[marketId]; delete wallets[marketTokenAddresses.realToken]; delete realTokenRoots[marketTokenAddresses.realToken]; delete tokensToMarkets[marketTokenAddresses.realToken]; delete marketTIP3Info[marketId]; } function transferTokensToWallet(address tonWallet, address tokenRoot, address userTip3Wallet, uint256 toPayout) external override view onlyTrusted { TvmCell empty; _transferTokensToWallet(tonWallet, tokenRoot, userTip3Wallet, uint128(toPayout), empty); } function _transferTokensToWallet(address tonWallet, address tokenRoot, address userTip3Wallet, uint128 toTransfer, TvmCell payload) internal view { ITONTokenWallet(wallets[tokenRoot]).transfer{ flag: MsgFlag.REMAINING_GAS }( userTip3Wallet, toTransfer, 0, tonWallet, true, payload ); } /*********************************************************************************************************/ // Wallet functionality /** * @param tokenRoot Address of token root to request wallet deploy */ function addWallet(address tokenRoot) private pure { IRootTokenContract(tokenRoot).deployEmptyWallet{ value: WCCostConstants.WALLET_DEPLOY_COST }( WCCostConstants.WALLET_DEPLOY_GRAMS, 0, address(this), address(this) ); IRootTokenContract(tokenRoot).getWalletAddress{ value: WCCostConstants.GET_WALLET_ADDRESS, callback: this.receiveTIP3WalletAddress }( 0, address(this) ); } /** * @param _wallet Receive deployed wallet address */ function receiveTIP3WalletAddress(address _wallet) external onlyExisingTIP3Root(msg.sender) { tvm.accept(); wallets[msg.sender] = _wallet; uint32 marketId = tokensToMarkets[msg.sender]; marketTIP3Info[marketId].realTokenWallet = _wallet; this.setReceiveCallback(_wallet); } function setReceiveCallback(address _wallet) external { require(msg.sender == address(this)); tvm.accept(); ITONTokenWallet(_wallet).setReceiveCallback{ value: WCCostConstants.SET_RECEIVE_CALLBACK }( address(this), true ); } function tokensReceivedCallback( address token_wallet, address token_root, uint128 amount, uint256, // sender_public_key, address sender_address, address sender_wallet, address, // original_gas_to, uint128, // updated_balance, TvmCell payload ) external override onlyOwnWallet(token_root, msg.sender) { tvm.rawReserve(msg.value, 2); TvmSlice ts = payload.toSlice(); if ( ts.bits() == 8 && ts.refs() == 1 ) { uint8 operation = ts.decode(uint8); TvmSlice args = ts.loadRefAsSlice(); if (operation == OperationCodes.SUPPLY_TOKENS) { TvmBuilder tb; tb.store(sender_address); tb.store(uint256(amount)); MarketAggregator(marketAddress).performOperationWalletController{ flag: MsgFlag.REMAINING_GAS }(operation, token_root, tb.toCell()); } else if (operation == OperationCodes.REPAY_TOKENS) { TvmBuilder tb; tb.store(sender_address); tb.store(sender_wallet); tb.store(uint256(amount)); MarketAggregator(marketAddress).performOperationWalletController{ flag: MsgFlag.REMAINING_GAS }(operation, token_root, tb.toCell()); } else if (operation == OperationCodes.LIQUIDATE_TOKENS) { (address targetUser, uint32 marketToLiquidate) = args.decode(address, uint32); TvmBuilder tb; TvmBuilder amountStorage; tb.store(sender_address); tb.store(targetUser); tb.store(sender_wallet); amountStorage.store(marketToLiquidate); amountStorage.store(uint256(amount)); tb.store(amountStorage.toCell()); MarketAggregator(marketAddress).performOperationWalletController{ flag: MsgFlag.REMAINING_GAS }(operation, token_root, tb.toCell()); } else { _transferTokensToWallet(sender_address, token_root, sender_wallet, amount, payload); } } else { _transferTokensToWallet(sender_address, token_root, sender_wallet, amount, payload); } } /*********************************************************************************************************/ // Getter functions function getRealTokenRoots() external override view responsible returns(mapping(address => bool)) { return {flag: MsgFlag.REMAINING_GAS} realTokenRoots; } function getWallets() external override view responsible returns(mapping(address => address)) { return {flag: MsgFlag.REMAINING_GAS} wallets; } function getMarketAddresses(uint32 marketId) external override view responsible returns(MarketTokenAddresses) { return {flag: MsgFlag.REMAINING_GAS} marketTIP3Info[marketId]; } function getAllMarkets() external override view responsible returns(mapping(uint32 => MarketTokenAddresses)) { return {flag: MsgFlag.REMAINING_GAS} marketTIP3Info; } /*********************************************************************************************************/ // modifiers modifier onlyMarket() { require(msg.sender == marketAddress, WalletControllerErrorCodes.ERROR_MSG_SENDER_IS_NOT_MARKET); _; } modifier onlyTrusted() { require( (msg.sender == marketAddress) ); _; } /** * @param tokenRoot Root address of TIP-3 token * @param tokenWallet Address of TIP-3 wallet */ modifier onlyOwnWallet(address tokenRoot, address tokenWallet) { require(wallets[tokenRoot] == tokenWallet, WalletControllerErrorCodes.ERROR_MSG_SENDER_IS_NOT_OWN_WALLET); _; } /** * @param rootAddress msg.sender parameter */ modifier onlyExisingTIP3Root(address rootAddress) { require(wallets.exists(rootAddress), WalletControllerErrorCodes.ERROR_TIP3_ROOT_IS_UNKNOWN); _; } /*********************************************************************************************************/ // Functions for payload creation function createSupplyPayload() external override pure returns(TvmCell) { TvmBuilder tb; tb.store(OperationCodes.SUPPLY_TOKENS); TvmBuilder op; tb.store(op.toCell()); return tb.toCell(); } function createRepayPayload() external override pure returns(TvmCell) { TvmBuilder tb; tb.store(OperationCodes.REPAY_TOKENS); TvmBuilder op; tb.store(op.toCell()); return tb.toCell(); } function createLiquidationPayload(address targetUser, uint32 marketId) external override pure returns(TvmCell) { TvmBuilder tb; tb.store(OperationCodes.LIQUIDATE_TOKENS); TvmBuilder op; op.store(targetUser); op.store(marketId); tb.store(op.toCell()); return tb.toCell(); } }
_wallet Receive deployed wallet address/
function receiveTIP3WalletAddress(address _wallet) external onlyExisingTIP3Root(msg.sender) { tvm.accept(); wallets[msg.sender] = _wallet; uint32 marketId = tokensToMarkets[msg.sender]; marketTIP3Info[marketId].realTokenWallet = _wallet; this.setReceiveCallback(_wallet); }
13,076,376
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract WildEXOplanet is ERC721, EIP712, Ownable{ using Counters for Counters.Counter; using ECDSA for bytes32; using Strings for uint256; using SafeMath for uint256; //Whitelist sale signer address WHITELIST_SIGNER = 0x093423fa2a98b1c7752a9122b7DD7426837c9ad9; Counters.Counter private _tokenIds; //baseuri for the tokens. string[] public tierBaseUris = [ 'ipfs://QmawPbpJZvfAkaz4G63yYdajQqfsXzctNxqfm38RKQiUHf/', 'ipfs://QmdSqPfwrFCqi3p1yqhh5YeemHokuY4UJgaAv5oYfCWWsq/', 'ipfs://QmVxFJFt3FK4s1UsWeL9qmJi4yQ51waTBKzEW9g4bsgxCz/', 'ipfs://QmZPmMb84CTEY5CDnAXRNHWiy1V5xFm1XzNaaUGGkvCdvU/', 'ipfs://QmRNBfxdPHHrL9otKsDgAWw3KrSfot2AVVChCnTJG1TjhX/' ]; //Minting start time in uinx-epoch [phase 1 start, phase 2 start] uint256[] public tierStartMintTimes = [1645020000, 1647374400]; //Minting ending time in unix-epoch [phase 1 end, phase 2 end] uint256[] public tierMintEndTimes = [1645106400, 1647460800]; //Minting tier fee uint256[] public tierMintFees = [0.25 ether, 0.7 ether, 1.1 ether, 1.5 ether, 2.5 ether]; //Max supply for each tier uint256[] public tierMaxSupply = [6907, 1498, 898, 498, 198]; //Running supply for each tier uint256[] public tierRunningSupply = [0,0,0,0,0]; //Tier mapping for the token mapping(uint256 => uint8) public tokenTier; //Mapping for different token id to their real token id in tier. mapping(uint256 => uint256) public realTokenIds; //Public giveaway token baseuris string[] public giveawayBaseUris = [ 'ipfs://QmYoCBBQu7qwhJNw6ti9gxUhhHw2zLd9qZYELP93WKsUqL/', 'ipfs://QmZArfk8EfP6fNtZCRV8eJiuPLHYRFf4X8SxjmZtkSEpfH/', 'ipfs://QmPVJW9YCj9Rsv7pXquKm5HcBm2LAvcHRdWQvkyvmYroYd/', 'ipfs://QmerqyWsXSum5kXCcReWAzRWfGHXpTuM6moQsEdK9iGmQV/' ]; //Total giveaway for the each tiers uint8[] public totalGiveaway = [24, 24, 24, 27]; //Total giveaway for each tiers uint8[] public giveawayCompleted = [0,0,0,0]; //Whitelist mint fee uint256 public whitelistMintFee = 0.2 ether; //Whitelist disable time uint256 public whitelistSaleDisableTime = 1645016400; uint256 public whitelistSaleStartTime = 1644930000; //Reveal time for Phase 1 and Phase 2 tokens uint256[] public revealTime = [1645110000, 1647460800]; //Maximum supply of the NFT uint128 public maxSupply = 9999; //Counts the successful total giveaway uint256 public giveawayDoneCount = 0; //claimed bitmask for whitelist sale mapping(uint256 => uint256) public whitelistSaleClaimBitMask; //number of nft in wallet //tier => address => number mapping(uint8 => mapping(address => uint8)) public nftNumber; //Events event WhiteListSale(uint256 tokenId, address wallet); event Giveaway(uint256 tokenId, address wallet); constructor() ERC721("Wild EXOplanet", "WEXO") EIP712("Wild EXOplanet", "1.0.0"){} ///@notice Mint the token to the address sent ///@param to address to mint token ///@param amount of token to mint ///@param tier tier of token to mint function mint(address to, uint8 amount, uint8 tier) public payable { if(tier == 0){ require(block.timestamp <= tierMintEndTimes[0], "NFT: Phase 1 Mint Ended!"); require(block.timestamp >= tierStartMintTimes[0], "NFT: Phase 1 Mint Not Started!"); } else{ require(block.timestamp <= tierMintEndTimes[1], "NFT: Public sale already ended!"); require(block.timestamp >= tierStartMintTimes[1], "NFT: Public sale Not Started!"); } require(tierRunningSupply[tier] < tierMaxSupply[tier], "NFT: Max Supply Of NFT reached!"); require(nftNumber[tier][to]+amount <= 2, "NFT: NFT wallet maximum capacity exceeded!!"); require(msg.value >= tierMintFees[tier]*amount, "NFT: Not enough Minting Fee!"); for(uint8 i = 0; i<amount; i++){ _tokenIds.increment(); uint256 newTokenId = _tokenIds.current().add(99); tierRunningSupply[tier] += 1; realTokenIds[newTokenId] = tierRunningSupply[tier]; tokenTier[newTokenId] = tier; _mint(to, newTokenId); } nftNumber[tier][to] += amount; } ///@notice Whitelist user claims for sales ///@param _signature signature signed by whitelist signer ///@param to account to Mint NFT ///@param _nftIndex index of NFT for claim function claimWhitelistSale(bytes[] calldata _signature, address to, uint256[] calldata _nftIndex) external payable{ require(block.timestamp >= whitelistSaleStartTime, "NFT: Whitelist sale not started!"); require(block.timestamp <= whitelistSaleDisableTime, "NFT: Whitelist sale ended!"); require(tierRunningSupply[0] < tierMaxSupply[0], "NFT: Max Supply Of NFT reached!"); require(nftNumber[0][to] + _nftIndex.length <=2, "NFT: Max NFT already minted!"); require(msg.value >= whitelistMintFee * _nftIndex.length, "NFT: Not enough Mint Fee!"); for(uint256 i=0;i< _nftIndex.length; i++){ require(!isClaimed(_nftIndex[i]), "NFT: Token already claimed!"); require(_verify(_hash(to, _nftIndex[i]), _signature[i]), "NFT: Invalid Claiming!"); _setClaimed(_nftIndex[i]); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current().add(99); tokenTier[newTokenId] = 0; _mint(to, newTokenId); nftNumber[0][to] += 1; tierRunningSupply[0]+=1; realTokenIds[newTokenId] = tierRunningSupply[0]; emit WhiteListSale(newTokenId, to); } } ///@notice Used by the team for giveaway ///@param _userAddress giveaway user addresses ///@param _tokenTiers token tier to mint function claimReserve(address[] memory _userAddress, uint8[] memory _tokenTiers) external onlyOwner{ require(_tokenTiers.length == _userAddress.length, "NFT: Token Tiers and User Address length mismatch!"); for(uint8 i=0; i<_tokenTiers.length; i++){ address currentUser = _userAddress[i]; uint8 currentTier = _tokenTiers[i]; require(nftNumber[currentTier][currentUser]+1 <= 2, "NFT: NFT wallet maximum capacity exceeded!"); require(giveawayCompleted[currentTier] < totalGiveaway[currentTier], "NFT: Giveaway amount exceeded!"); giveawayCompleted[currentTier] += 1 ; giveawayDoneCount += 1; nftNumber[currentTier][currentUser] +=1 ; realTokenIds[giveawayDoneCount] = giveawayCompleted[currentTier]; tokenTier[giveawayDoneCount] = currentTier; _mint(currentUser, giveawayDoneCount); emit Giveaway(giveawayDoneCount, currentUser); } } ///@notice Checks if the nft index is claimed or not ///@param _nftIndex NFT index for claiming function isClaimed(uint256 _nftIndex) public view returns (bool) { uint256 wordIndex = _nftIndex / 256; uint256 bitIndex = _nftIndex % 256; uint256 mask = 1 << bitIndex; return whitelistSaleClaimBitMask[wordIndex] & mask == mask; } ///@notice Sets claimed nftIndex function _setClaimed(uint256 _nftIndex) internal{ uint256 wordIndex = _nftIndex / 256; uint256 bitIndex = _nftIndex % 256; uint256 mask = 1 << bitIndex; whitelistSaleClaimBitMask[wordIndex] |= mask; } ///@notice hash the data for signing data function _hash(address _account, uint256 _nftIndex) internal view returns (bytes32) { return _hashTypedDataV4(keccak256(abi.encode( keccak256("NFT(address _account,uint256 _nftIndex)"), _account, _nftIndex ))); } ///@notice verifies data for signature function _verify(bytes32 digest, bytes memory signature) internal view returns (bool) { return SignatureChecker.isValidSignatureNow(WHITELIST_SIGNER, digest, signature); } ///@notice Return Base Uri for the token function _baseURI() internal view virtual override returns (string memory) { return tierBaseUris[0]; } ///@notice Return base uri for token ///@param _tokenId token id to return the metadata uri function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "NFT: URI query for nonexistent token"); string memory uri; uint8 tier = tokenTier[_tokenId]; uint256 realTokenId = realTokenIds[_tokenId]; if(_tokenId <= 99){ //giveaway uri = bytes(giveawayBaseUris[tier]).length > 0 ? string(abi.encodePacked(giveawayBaseUris[tier], realTokenId.toString(), ".json")) : ""; } else{ //non give away if(tier > 0){ if(block.timestamp >= revealTime[1] ) uri = bytes(tierBaseUris[tier]).length > 0 ? string(abi.encodePacked(tierBaseUris[tier], realTokenId.toString(), ".json")) : ""; else uri = 'ipfs://QmdF2XaRXKSaFg1kcoQW566zMN1d8pba8VUb9wwxnsS8yt/'; } else{ if(block.timestamp >= revealTime[0]) uri = bytes(tierBaseUris[0]).length > 0 ? string(abi.encodePacked(tierBaseUris[0], realTokenId.toString(), ".json")) : ""; else uri = 'ipfs://QmdF2XaRXKSaFg1kcoQW566zMN1d8pba8VUb9wwxnsS8yt/'; } } return uri; } ///@notice Total supply of the token function totalSupply() public view virtual returns (uint256) { return maxSupply; } ///@notice Update Tier Mint Fee by Owner ///@param _updateFees updated fee for the different Tier function updatesTierMintFees(uint256[] memory _updateFees) external onlyOwner{ tierMintFees = _updateFees; } ///@notice Update Whitelist Sale mint fee ///@param _whitelistMintFee updated whitelist mint fee function updateWhiteListMintFee(uint256 _whitelistMintFee) external onlyOwner{ whitelistMintFee = _whitelistMintFee; } ///@notice Update Pase Minting start time ///@param _tierMintTimes updated Phase Minting start time function updateTierMintStartTimes(uint256[] memory _tierMintTimes) external onlyOwner{ tierStartMintTimes = _tierMintTimes; } ///@notice Update Phase Minting end time ///@param _tierMintTimes updated Phase Minting end time function updateTierMintEndTimes(uint256[] memory _tierMintTimes) external onlyOwner{ tierMintEndTimes = _tierMintTimes; } ///@notice Update Whitelist Sale disable time ///@param _disableTime Updated whitelist sale disable time function updateWhiteListDisableTime(uint256 _disableTime) external onlyOwner{ whitelistSaleDisableTime = _disableTime; } ///@notice Update Reveal Time for phases ///@param _revealTimes updated reveal time for the function updateRevealTime(uint256[] memory _revealTimes) external onlyOwner{ revealTime = _revealTimes; } ///@notice Withdraw Eth by the owner function withdraw() external payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) 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; address private immutable _CACHED_THIS; 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); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && 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 // OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; import "../Address.sol"; import "../../interfaces/IERC1271.sol"; /** * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and * ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with * smart contract wallets such as Argent and Gnosis. * * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change * through time. It could return true at block N and false at block N+1 (or the opposite). * * _Available since v4.1._ */ library SignatureChecker { function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns 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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Checks if the nft index is claimed or not _nftIndex NFT index for claiming
function isClaimed(uint256 _nftIndex) public view returns (bool) { uint256 wordIndex = _nftIndex / 256; uint256 bitIndex = _nftIndex % 256; uint256 mask = 1 << bitIndex; return whitelistSaleClaimBitMask[wordIndex] & mask == mask; }
559,648
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library 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/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/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 _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/IStaking.sol /* Staking interface EIP-900 staking interface https://github.com/gysr-io/core h/t https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md */ pragma solidity ^0.6.12; interface IStaking { // events event Staked( address indexed user, uint256 amount, uint256 total, bytes data ); event Unstaked( address indexed user, uint256 amount, uint256 total, bytes data ); /** * @notice stakes a certain amount of tokens, transferring this amount from the user to the contract * @param amount number of tokens to stake */ function stake(uint256 amount, bytes calldata) external; /** * @notice stakes a certain amount of tokens for an address, transfering this amount from the caller to the contract, on behalf of the specified address * @param user beneficiary address * @param amount number of tokens to stake */ function stakeFor( address user, uint256 amount, bytes calldata ) external; /** * @notice unstakes a certain amount of tokens, returning these tokens to the user * @param amount number of tokens to unstake */ function unstake(uint256 amount, bytes calldata) external; /** * @param addr the address of interest * @return the current total of tokens staked for an address */ function totalStakedFor(address addr) external view returns (uint256); /** * @return the current total amount of tokens staked by all users */ function totalStaked() external view returns (uint256); /** * @return the staking token for this staking contract */ function token() external view returns (address); /** * @return true if the staking contract support history */ function supportsHistory() external pure returns (bool); } // File: contracts/IGeyser.sol /* Geyser interface This defines the core Geyser contract interface as an extension to the standard IStaking interface https://github.com/gysr-io/core */ pragma solidity ^0.6.12; /** * @title Geyser interface */ abstract contract IGeyser is IStaking, Ownable { // events event RewardsDistributed(address indexed user, uint256 amount); event RewardsFunded( uint256 amount, uint256 duration, uint256 start, uint256 total ); event RewardsUnlocked(uint256 amount, uint256 total); event RewardsExpired(uint256 amount, uint256 duration, uint256 start); event GysrSpent(address indexed user, uint256 amount); event GysrWithdrawn(uint256 amount); // IStaking /** * @notice no support for history * @return false */ function supportsHistory() external override pure returns (bool) { return false; } // IGeyser /** * @return staking token for this Geyser */ function stakingToken() external virtual view returns (address); /** * @return reward token for this Geyser */ function rewardToken() external virtual view returns (address); /** * @notice fund Geyser by locking up reward tokens for distribution * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked */ function fund(uint256 amount, uint256 duration) external virtual; /** * @notice fund Geyser by locking up reward tokens for future distribution * @param amount number of reward tokens to lock up as funding * @param duration period (seconds) over which funding will be unlocked * @param start time (seconds) at which funding begins to unlock */ function fund( uint256 amount, uint256 duration, uint256 start ) external virtual; /** * @notice withdraw GYSR tokens applied during unstaking * @param amount number of GYSR to withdraw */ function withdraw(uint256 amount) external virtual; /** * @notice unstake while applying GYSR token for boosted rewards * @param amount number of tokens to unstake * @param gysr number of GYSR tokens to apply for boost */ function unstake( uint256 amount, uint256 gysr, bytes calldata ) external virtual; /** * @notice update accounting, unlock tokens, etc. */ function update() external virtual; /** * @notice clean geyser, expire old fundings, etc. */ function clean() external virtual; } // File: contracts/GeyserPool.sol /* Geyser token pool Simple contract to implement token pool of arbitrary ERC20 token. This is owned and used by a parent Geyser https://github.com/gysr-io/core h/t https://github.com/ampleforth/token-geyser */ pragma solidity ^0.6.12; contract GeyserPool is Ownable { using SafeERC20 for IERC20; IERC20 public token; constructor(address token_) public { token = IERC20(token_); } function balance() public view returns (uint256) { return token.balanceOf(address(this)); } function transfer(address to, uint256 value) external onlyOwner { token.safeTransfer(to, value); } } // File: contracts/MathUtils.sol /* Math utilities This library implements various logarithmic math utilies which support other contracts and specifically the GYSR multiplier calculation https://github.com/gysr-io/core h/t https://github.com/abdk-consulting/abdk-libraries-solidity */ pragma solidity ^0.6.12; library MathUtils { /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function logbase2(int128 x) internal pure returns (int128) { require(x > 0); int256 msb = 0; int256 xc = x; 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 result = (msb - 64) << 64; uint256 ux = uint256(x) << (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } /** * @notice calculate natural logarithm of x * @dev magic constant comes from ln(2) * 2^128 -> hex * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { require(x > 0); return int128( (uint256(logbase2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128 ); } /** * @notice calculate logarithm base 10 of x * @dev magic constant comes from log10(2) * 2^128 -> hex * @param x signed 64.64-bit fixed point number, require x > 0 * @return signed 64.64-bit fixed point number */ function logbase10(int128 x) internal pure returns (int128) { require(x > 0); return int128( (uint256(logbase2(x)) * 0x4d104d427de7fce20a6e420e02236748) >> 128 ); } // wrapper functions to allow testing function testlogbase2(int128 x) public pure returns (int128) { return logbase2(x); } function testlogbase10(int128 x) public pure returns (int128) { return logbase10(x); } } // File: contracts/Geyser.sol /* Geyser This implements the core Geyser contract, which allows for generalized staking, yield farming, and token distribution. This also implements the GYSR spending mechanic for boosted reward distribution. https://github.com/gysr-io/core h/t https://github.com/ampleforth/token-geyser */ pragma solidity ^0.6.12; /** * @title Geyser */ contract Geyser is IGeyser, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; using MathUtils for int128; // single stake by user struct Stake { uint256 shares; uint256 timestamp; } // summary of total user stake/shares struct User { uint256 shares; uint256 shareSeconds; uint256 lastUpdated; } // single funding/reward schedule struct Funding { uint256 amount; uint256 shares; uint256 unlocked; uint256 lastUpdated; uint256 start; uint256 end; uint256 duration; } // constants uint256 public constant BONUS_DECIMALS = 18; uint256 public constant INITIAL_SHARES_PER_TOKEN = 10**6; uint256 public constant MAX_ACTIVE_FUNDINGS = 16; // token pool fields GeyserPool private immutable _stakingPool; GeyserPool private immutable _unlockedPool; GeyserPool private immutable _lockedPool; Funding[] public fundings; // user staking fields mapping(address => User) public userTotals; mapping(address => Stake[]) public userStakes; // time bonus fields uint256 public immutable bonusMin; uint256 public immutable bonusMax; uint256 public immutable bonusPeriod; // global state fields uint256 public totalLockedShares; uint256 public totalStakingShares; uint256 public totalRewards; uint256 public totalGysrRewards; uint256 public totalStakingShareSeconds; uint256 public lastUpdated; // gysr fields IERC20 private immutable _gysr; /** * @param stakingToken_ the token that will be staked * @param rewardToken_ the token distributed to users as they unstake * @param bonusMin_ initial time bonus * @param bonusMax_ maximum time bonus * @param bonusPeriod_ period (in seconds) over which time bonus grows to max * @param gysr_ address for GYSR token */ constructor( address stakingToken_, address rewardToken_, uint256 bonusMin_, uint256 bonusMax_, uint256 bonusPeriod_, address gysr_ ) public { require( bonusMin_ <= bonusMax_, "Geyser: initial time bonus greater than max" ); _stakingPool = new GeyserPool(stakingToken_); _unlockedPool = new GeyserPool(rewardToken_); _lockedPool = new GeyserPool(rewardToken_); bonusMin = bonusMin_; bonusMax = bonusMax_; bonusPeriod = bonusPeriod_; _gysr = IERC20(gysr_); lastUpdated = block.timestamp; } // IStaking /** * @inheritdoc IStaking */ function stake(uint256 amount, bytes calldata) external override { _stake(msg.sender, msg.sender, amount); } /** * @inheritdoc IStaking */ function stakeFor( address user, uint256 amount, bytes calldata ) external override { _stake(msg.sender, user, amount); } /** * @inheritdoc IStaking */ function unstake(uint256 amount, bytes calldata) external override { _unstake(amount, 0); } /** * @inheritdoc IStaking */ function totalStakedFor(address addr) public override view returns (uint256) { if (totalStakingShares == 0) { return 0; } return totalStaked().mul(userTotals[addr].shares).div(totalStakingShares); } /** * @inheritdoc IStaking */ function totalStaked() public override view returns (uint256) { return _stakingPool.balance(); } /** * @inheritdoc IStaking * @dev redundant with stakingToken() in order to implement IStaking (EIP-900) */ function token() external override view returns (address) { return address(_stakingPool.token()); } // IGeyser /** * @inheritdoc IGeyser */ function stakingToken() public override view returns (address) { return address(_stakingPool.token()); } /** * @inheritdoc IGeyser */ function rewardToken() public override view returns (address) { return address(_unlockedPool.token()); } /** * @inheritdoc IGeyser */ function fund(uint256 amount, uint256 duration) public override { fund(amount, duration, block.timestamp); } /** * @inheritdoc IGeyser */ function fund( uint256 amount, uint256 duration, uint256 start ) public override onlyOwner { // validate require(amount > 0, "Geyser: funding amount is zero"); require(start >= block.timestamp, "Geyser: funding start is past"); require( fundings.length < MAX_ACTIVE_FUNDINGS, "Geyser: exceeds max active funding schedules" ); // update bookkeeping _update(msg.sender); // mint shares at current rate uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(INITIAL_SHARES_PER_TOKEN); totalLockedShares = totalLockedShares.add(mintedLockedShares); // create new funding fundings.push( Funding({ amount: amount, shares: mintedLockedShares, unlocked: 0, lastUpdated: start, start: start, end: start.add(duration), duration: duration }) ); // do transfer of funding _lockedPool.token().safeTransferFrom( msg.sender, address(_lockedPool), amount ); emit RewardsFunded(amount, duration, start, totalLocked()); } /** * @inheritdoc IGeyser */ function withdraw(uint256 amount) external override onlyOwner { require(amount > 0, "Geyser: withdraw amount is zero"); require( amount <= _gysr.balanceOf(address(this)), "Geyser: withdraw amount exceeds balance" ); // do transfer _gysr.safeTransfer(msg.sender, amount); emit GysrWithdrawn(amount); } /** * @inheritdoc IGeyser */ function unstake( uint256 amount, uint256 gysr, bytes calldata ) external override { _unstake(amount, gysr); } /** * @inheritdoc IGeyser */ function update() external override nonReentrant { _update(msg.sender); } /** * @inheritdoc IGeyser */ function clean() external override onlyOwner { // update bookkeeping _update(msg.sender); // check for stale funding schedules to expire uint256 removed = 0; uint256 originalSize = fundings.length; for (uint256 i = 0; i < originalSize; i++) { Funding storage funding = fundings[i.sub(removed)]; uint256 idx = i.sub(removed); if (_unlockable(idx) == 0 && block.timestamp >= funding.end) { emit RewardsExpired( funding.amount, funding.duration, funding.start ); // remove at idx by copying last element here, then popping off last // (we don't care about order) fundings[idx] = fundings[fundings.length.sub(1)]; fundings.pop(); removed = removed.add(1); } } } // Geyser /** * @dev internal implementation of staking methods * @param staker address to do deposit of staking tokens * @param beneficiary address to gain credit for this stake operation * @param amount number of staking tokens to deposit */ function _stake( address staker, address beneficiary, uint256 amount ) private nonReentrant { // validate require(amount > 0, "Geyser: stake amount is zero"); require( beneficiary != address(0), "Geyser: beneficiary is zero address" ); // mint staking shares at current rate uint256 mintedStakingShares = (totalStakingShares > 0) ? totalStakingShares.mul(amount).div(totalStaked()) : amount.mul(INITIAL_SHARES_PER_TOKEN); require(mintedStakingShares > 0, "Geyser: stake amount too small"); // update bookkeeping _update(beneficiary); // update user staking info User storage user = userTotals[beneficiary]; user.shares = user.shares.add(mintedStakingShares); user.lastUpdated = block.timestamp; userStakes[beneficiary].push( Stake(mintedStakingShares, block.timestamp) ); // add newly minted shares to global total totalStakingShares = totalStakingShares.add(mintedStakingShares); // transactions _stakingPool.token().safeTransferFrom( staker, address(_stakingPool), amount ); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); } /** * @dev internal implementation of unstaking methods * @param amount number of tokens to unstake * @param gysr number of GYSR tokens applied to unstaking operation * @return number of reward tokens distributed */ function _unstake(uint256 amount, uint256 gysr) private nonReentrant returns (uint256) { // validate require(amount > 0, "Geyser: unstake amount is zero"); require( totalStakedFor(msg.sender) >= amount, "Geyser: unstake amount exceeds balance" ); // update bookkeeping _update(msg.sender); // do unstaking, first-in last-out, respecting time bonus uint256 timeWeightedShareSeconds = _unstakeFirstInLastOut(amount); // compute and apply GYSR token bonus uint256 gysrWeightedShareSeconds = gysrBonus(gysr) .mul(timeWeightedShareSeconds) .div(10**BONUS_DECIMALS); uint256 rewardAmount = totalUnlocked() .mul(gysrWeightedShareSeconds) .div(totalStakingShareSeconds.add(gysrWeightedShareSeconds)); // update global stats for distributions if (gysr > 0) { totalGysrRewards = totalGysrRewards.add(rewardAmount); } totalRewards = totalRewards.add(rewardAmount); // transactions _stakingPool.transfer(msg.sender, amount); emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), ""); if (rewardAmount > 0) { _unlockedPool.transfer(msg.sender, rewardAmount); emit RewardsDistributed(msg.sender, rewardAmount); } if (gysr > 0) { _gysr.safeTransferFrom(msg.sender, address(this), gysr); emit GysrSpent(msg.sender, gysr); } return rewardAmount; } /** * @dev helper function to actually execute unstaking, first-in last-out, while computing and applying time bonus. This function also updates user and global totals for shares and share-seconds. * @param amount number of staking tokens to withdraw * @return time bonus weighted staking share seconds */ function _unstakeFirstInLastOut(uint256 amount) private returns (uint256) { uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div( totalStaked() ); require(stakingSharesToBurn > 0, "Geyser: unstake amount too small"); // redeem from most recent stake and go backwards in time. uint256 shareSecondsToBurn = 0; uint256 sharesLeftToBurn = stakingSharesToBurn; uint256 bonusWeightedShareSeconds = 0; Stake[] storage stakes = userStakes[msg.sender]; while (sharesLeftToBurn > 0) { Stake storage lastStake = stakes[stakes.length - 1]; uint256 stakeTime = block.timestamp.sub(lastStake.timestamp); uint256 bonus = timeBonus(stakeTime); if (lastStake.shares <= sharesLeftToBurn) { // fully redeem a past stake bonusWeightedShareSeconds = bonusWeightedShareSeconds.add( lastStake.shares.mul(stakeTime).mul(bonus).div( 10**BONUS_DECIMALS ) ); shareSecondsToBurn = shareSecondsToBurn.add( lastStake.shares.mul(stakeTime) ); sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.shares); stakes.pop(); } else { // partially redeem a past stake bonusWeightedShareSeconds = bonusWeightedShareSeconds.add( sharesLeftToBurn.mul(stakeTime).mul(bonus).div( 10**BONUS_DECIMALS ) ); shareSecondsToBurn = shareSecondsToBurn.add( sharesLeftToBurn.mul(stakeTime) ); lastStake.shares = lastStake.shares.sub(sharesLeftToBurn); sharesLeftToBurn = 0; } } // update user totals User storage user = userTotals[msg.sender]; user.shareSeconds = user.shareSeconds.sub(shareSecondsToBurn); user.shares = user.shares.sub(stakingSharesToBurn); user.lastUpdated = block.timestamp; // update global totals totalStakingShareSeconds = totalStakingShareSeconds.sub( shareSecondsToBurn ); totalStakingShares = totalStakingShares.sub(stakingSharesToBurn); return bonusWeightedShareSeconds; } /** * @dev internal implementation of update method * @param addr address for user accounting update */ function _update(address addr) private { _unlockTokens(); // global accounting uint256 deltaTotalShareSeconds = (block.timestamp.sub(lastUpdated)).mul( totalStakingShares ); totalStakingShareSeconds = totalStakingShareSeconds.add( deltaTotalShareSeconds ); lastUpdated = block.timestamp; // user accounting User storage user = userTotals[addr]; uint256 deltaUserShareSeconds = (block.timestamp.sub(user.lastUpdated)) .mul(user.shares); user.shareSeconds = user.shareSeconds.add(deltaUserShareSeconds); user.lastUpdated = block.timestamp; } /** * @dev unlocks reward tokens based on funding schedules */ function _unlockTokens() private { uint256 tokensToUnlock = 0; uint256 lockedTokens = totalLocked(); if (totalLockedShares == 0) { // handle any leftover tokensToUnlock = lockedTokens; } else { // normal case: unlock some shares from each funding schedule uint256 sharesToUnlock = 0; for (uint256 i = 0; i < fundings.length; i++) { uint256 shares = _unlockable(i); Funding storage funding = fundings[i]; if (shares > 0) { funding.unlocked = funding.unlocked.add(shares); funding.lastUpdated = block.timestamp; sharesToUnlock = sharesToUnlock.add(shares); } } tokensToUnlock = sharesToUnlock.mul(lockedTokens).div( totalLockedShares ); totalLockedShares = totalLockedShares.sub(sharesToUnlock); } if (tokensToUnlock > 0) { _lockedPool.transfer(address(_unlockedPool), tokensToUnlock); emit RewardsUnlocked(tokensToUnlock, totalUnlocked()); } } /** * @dev helper function to compute updates to funding schedules * @param idx index of the funding * @return the number of unlockable shares */ function _unlockable(uint256 idx) private view returns (uint256) { Funding storage funding = fundings[idx]; // funding schedule is in future if (block.timestamp < funding.start) { return 0; } // empty if (funding.unlocked >= funding.shares) { return 0; } // handle zero-duration period or leftover dust from integer division if (block.timestamp >= funding.end) { return funding.shares.sub(funding.unlocked); } return (block.timestamp.sub(funding.lastUpdated)).mul(funding.shares).div( funding.duration ); } /** * @notice compute time bonus earned as a function of staking time * @param time length of time for which the tokens have been staked * @return bonus multiplier for time */ function timeBonus(uint256 time) public view returns (uint256) { if (time >= bonusPeriod) { return uint256(10**BONUS_DECIMALS).add(bonusMax); } // linearly interpolate between bonus min and bonus max uint256 bonus = bonusMin.add( (bonusMax.sub(bonusMin)).mul(time).div(bonusPeriod) ); return uint256(10**BONUS_DECIMALS).add(bonus); } /** * @notice compute GYSR bonus as a function of usage ratio and GYSR spent * @param gysr number of GYSR token applied to bonus * @return multiplier value */ function gysrBonus(uint256 gysr) public view returns (uint256) { if (gysr == 0) { return 10**BONUS_DECIMALS; } require( gysr >= 10**BONUS_DECIMALS, "Geyser: GYSR amount is between 0 and 1" ); uint256 buffer = uint256(10**(BONUS_DECIMALS - 2)); // 0.01 uint256 r = ratio().add(buffer); uint256 x = gysr.add(buffer); return uint256(10**BONUS_DECIMALS).add( uint256(int128(x.mul(2**64).div(r)).logbase10()) .mul(10**BONUS_DECIMALS) .div(2**64) ); } /** * @return portion of rewards which have been boosted by GYSR token */ function ratio() public view returns (uint256) { if (totalRewards == 0) { return 0; } return totalGysrRewards.mul(10**BONUS_DECIMALS).div(totalRewards); } // Geyser -- informational functions /** * @return total number of locked reward tokens */ function totalLocked() public view returns (uint256) { return _lockedPool.balance(); } /** * @return total number of unlocked reward tokens */ function totalUnlocked() public view returns (uint256) { return _unlockedPool.balance(); } /** * @return number of active funding schedules */ function fundingCount() public view returns (uint256) { return fundings.length; } /** * @param addr address of interest * @return number of active stakes for user */ function stakeCount(address addr) public view returns (uint256) { return userStakes[addr].length; } /** * @notice preview estimated reward distribution for full unstake with no GYSR applied * @return estimated reward * @return estimated overall multiplier * @return estimated raw user share seconds that would be burned * @return estimated total unlocked rewards */ function preview() public view returns ( uint256, uint256, uint256, uint256 ) { return preview(msg.sender, totalStakedFor(msg.sender), 0); } /** * @notice preview estimated reward distribution for unstaking * @param addr address of interest for preview * @param amount number of tokens that would be unstaked * @param gysr number of GYSR tokens that would be applied * @return estimated reward * @return estimated overall multiplier * @return estimated raw user share seconds that would be burned * @return estimated total unlocked rewards */ function preview( address addr, uint256 amount, uint256 gysr ) public view returns ( uint256, uint256, uint256, uint256 ) { // compute expected updates to global totals uint256 deltaUnlocked = 0; if (totalLockedShares != 0) { uint256 sharesToUnlock = 0; for (uint256 i = 0; i < fundings.length; i++) { sharesToUnlock = sharesToUnlock.add(_unlockable(i)); } deltaUnlocked = sharesToUnlock.mul(totalLocked()).div( totalLockedShares ); } // no need for unstaking/rewards computation if (amount == 0) { return (0, 0, 0, totalUnlocked().add(deltaUnlocked)); } // check unstake amount require( amount <= totalStakedFor(addr), "Geyser: preview amount exceeds balance" ); // compute unstake amount in shares uint256 shares = totalStakingShares.mul(amount).div(totalStaked()); require(shares > 0, "Geyser: preview amount too small"); uint256 rawShareSeconds = 0; uint256 timeBonusShareSeconds = 0; // compute first-in-last-out, time bonus weighted, share seconds uint256 i = userStakes[addr].length.sub(1); while (shares > 0) { Stake storage s = userStakes[addr][i]; uint256 time = block.timestamp.sub(s.timestamp); if (s.shares < shares) { rawShareSeconds = rawShareSeconds.add(s.shares.mul(time)); timeBonusShareSeconds = timeBonusShareSeconds.add( s.shares.mul(time).mul(timeBonus(time)).div( 10**BONUS_DECIMALS ) ); shares = shares.sub(s.shares); } else { rawShareSeconds = rawShareSeconds.add(shares.mul(time)); timeBonusShareSeconds = timeBonusShareSeconds.add( shares.mul(time).mul(timeBonus(time)).div( 10**BONUS_DECIMALS ) ); break; } // this will throw on underflow i = i.sub(1); } // apply gysr bonus uint256 gysrBonusShareSeconds = gysrBonus(gysr) .mul(timeBonusShareSeconds) .div(10**BONUS_DECIMALS); // compute rewards based on expected updates uint256 expectedTotalShareSeconds = totalStakingShareSeconds .add((block.timestamp.sub(lastUpdated)).mul(totalStakingShares)) .add(gysrBonusShareSeconds) .sub(rawShareSeconds); uint256 reward = (totalUnlocked().add(deltaUnlocked)) .mul(gysrBonusShareSeconds) .div(expectedTotalShareSeconds); // compute effective bonus uint256 bonus = uint256(10**BONUS_DECIMALS) .mul(gysrBonusShareSeconds) .div(rawShareSeconds); return ( reward, bonus, rawShareSeconds, totalUnlocked().add(deltaUnlocked) ); } }
return total number of locked reward tokens/
function totalLocked() public view returns (uint256) { return _lockedPool.balance(); }
303,636
./full_match/80001/0x3d55Cc514ddEECbb73eB9Ff193e463ed35a45071/sources/contracts/protocol/modules/DextfTradeModule.sol
Update the fund positions according to the trades just executed _fund Address of the fund subject of the position update _tradeComponents The components to be updated _fundTotalSupply The observed fund total supply _preTradePositionBalances The fund balance for each given component, observed before the trade/ Edit the inbound-component positions
function _updateFundPositions( ISetToken _fund, TradeComponent[] memory _tradeComponents, uint256 _fundTotalSupply, uint256[] memory _preTradePositionBalances ) internal { for (uint256 i = 0; i < _tradeComponents.length; i++) { _fund.calculateAndEditDefaultPosition( _tradeComponents[i].componentAddress, _fundTotalSupply, _preTradePositionBalances[i] ); } }
5,576,457
pragma solidity ^0.4.16; /** * @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; } } /** * @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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { 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) constant 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); 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 recieve 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 returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title TokenDestructible: * @author Remco Bloemen <<span class="__cf_email__" data-cfemail="89fbece4eae6c9bb">[email&#160;protected]</span>π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { function TokenDestructible() payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } /** * @title JesusCoin 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 JesusCoin is StandardToken, Ownable, TokenDestructible { string public name = "Jesus Coin"; uint8 public decimals = 18; string public symbol = "JC"; string public version = "0.2"; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end block, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract JesusCrowdsale is Ownable, Pausable, TokenDestructible { using SafeMath for uint256; JesusCoin public token; uint256 constant public START = 1507755600; // +new Date(2017, 9, 12) / 1000 uint256 constant public END = 1513029600; // +new Date(2017, 11, 12) / 1000 address public wallet = 0x61cc738Aef5D67ec7954B03871BA13dDe5B87DE8; address public bountyWallet = 0x03D299B68f8a0e47edd0609FB2B77FC0F2e4fa9e; uint256 public weiRaised; bool public bountyDistributed; function JesusCrowdsale() payable { token = new JesusCoin(); } // function to get the price of the token // returns how many token units a buyer gets per wei, needs to be divided by 10 function getRate() constant returns (uint8) { if (block.timestamp < START) return 166; // presale, 40% bonus else if (block.timestamp <= START + 6 days) return 162; // day 1 to 6, 35% bonus else if (block.timestamp <= START + 13 days) return 156; // day 7 to 13, 30% bonus else if (block.timestamp <= START + 20 days) return 150; // day 14 to 20, 25% bonus else if (block.timestamp <= START + 27 days) return 144; // day 21 to 27, 20% bonus else if (block.timestamp <= START + 34 days) return 138; // day 28 to 34, 15% bonus else if (block.timestamp <= START + 41 days) return 132; // day 35 to 41, 10% bonus else if (block.timestamp <= START + 48 days) return 126; // day 42 to 48, 5% bonus return 120; // no bonus } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) whenNotPaused() payable { require(beneficiary != 0x0); require(msg.value != 0); require(block.timestamp <= END); uint256 weiAmount = msg.value; weiRaised = weiRaised.add(weiAmount); uint256 tokens = weiAmount.mul(getRate()).div(10); token.mint(beneficiary, tokens); wallet.transfer(msg.value); } function distributeBounty() onlyOwner { require(!bountyDistributed); require(block.timestamp >= END); // calculate token amount to be minted for bounty uint256 amount = weiRaised.div(100).mul(2); // 2% of all tokens token.mint(bountyWallet, amount); bountyDistributed = true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { require(bountyDistributed); require(block.timestamp >= END); return token.finishMinting(); } }
Function to stop minting new tokens. return True if the operation was successful./
function finishMinting() onlyOwner returns (bool) { require(bountyDistributed); require(block.timestamp >= END); return token.finishMinting(); }
7,801,075
/** *Submitted for verification at Etherscan.io on 2019-12-27 */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** * Implements a "lock" feature with a cooldown */ library Blocklock { struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } function setCooldownDuration(State storage self, uint256 cooldownDuration) public { self.cooldownDuration = cooldownDuration; } function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt + self.cooldownDuration ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self) + self.cooldownDuration; } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt + self.lockDuration; // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @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); } /** * @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; } } /** * @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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @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. */ contract ReentrancyGuard is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } uint256[50] private ______gap; } /** * @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(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); 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), "Roles: account is the zero address"); return role.bearer[account]; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { if (_upperBound == 0) { return 0; } uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (block.number == 0) { // No existing node. //injected CONTRACT AFFECTED BY MINERS if (block.number != 0) { // Non zero value. //injected CONTRACT AFFECTED BY MINERS // Append. // Add node. if (block.number == 0) { // No vacant spots. //injected CONTRACT AFFECTED BY MINERS // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (block.number == 0) { // Zero value. //injected CONTRACT AFFECTED BY MINERS // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (block.timestamp != tree.nodes[treeIndex]) { // New, non zero value. //injected CONTRACT AFFECTED BY MINERS // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if (block.number >= tree.nodes.length) { //injected CONTRACT AFFECTED BY MINERS startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (block.timestamp < _count) { //injected CONTRACT AFFECTED BY MINERS values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (block.timestamp >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. //injected CONTRACT AFFECTED BY MINERS else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (block.gaslimit == 0) value = 0; //injected CONTRACT AFFECTED BY MINERS else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_LEAVES = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the first Draw index that an address deposited to. */ mapping(address => uint256) usersFirstDrawIndex; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) usersSecondDrawIndex; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_LEAVES); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_LEAVES); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; // if this is the users first draw, set it if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS self.usersFirstDrawIndex[_addr] = openDrawIndex; // otherwise, if the first draw is not this draw } else if (block.gaslimit != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // if a second draw does not exist if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS // set the second draw to the current draw self.usersSecondDrawIndex[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (block.timestamp != openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // merge it into the first draw, and update the second draw index to this one uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); uint256 secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(secondAmount), _addr); drawSet(self, secondDrawIndex, 0, _addr); self.usersSecondDrawIndex[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; // if they have a committed balance if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(_amount), _addr); } else { // they must not have any committed balance self.usersSecondDrawIndex[_addr] = firstDrawIndex; self.usersFirstDrawIndex[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.usersFirstDrawIndex[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, firstDrawIndex, 0, _addr); delete self.usersFirstDrawIndex[_addr]; } if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, secondDrawIndex, 0, _addr); delete self.usersSecondDrawIndex[_addr]; } } function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; uint256 firstAmount = 0; uint256 secondAmount = 0; uint256 total = 0; if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); total = total.add(secondAmount); } if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); total = total.add(firstAmount); } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (block.timestamp > firstAmount) { //injected CONTRACT AFFECTED BY MINERS uint256 secondRemaining = remaining.sub(firstAmount); drawSet(self, secondDrawIndex, secondRemaining, _addr); } else if (block.gaslimit > 0) { // else delete the second amount if it exists //injected CONTRACT AFFECTED BY MINERS delete self.usersSecondDrawIndex[_addr]; drawSet(self, secondDrawIndex, 0, _addr); } // if the first amount needs to be destroyed if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS delete self.usersFirstDrawIndex[_addr]; drawSet(self, firstDrawIndex, 0, _addr); } else if (block.number < firstAmount) { //injected CONTRACT AFFECTED BY MINERS drawSet(self, firstDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), bytes32(uint256(_addr)))); } if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (block.gaslimit != _amount) { //injected CONTRACT AFFECTED BY MINERS // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (block.timestamp != self.openDrawIndex) { //injected CONTRACT AFFECTED BY MINERS // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); uint256 drawIndex = uint256(self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token)); uint256 drawSupply = self.sortitionSumTrees.total(bytes32(drawIndex)); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(bytes32(drawIndex), drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { return draw(self, UniformRandomNumber.uniform(uint256(_entropy), committedSupply(self))); } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; BasePool internal _pool; function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } function pool() public view returns (address) { return address(_pool); } function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, true); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDeposit(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck Whether the recipient, when a contract, *must* have a IERC777Recipient implementor */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event Paused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event Unpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State drawState; /** * A structure containing the administrators */ Roles.Role admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(_poolToken.pool() == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Commits the current draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (block.number != 0) { //injected CONTRACT AFFECTED BY MINERS emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt)) */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was combined with the revealed secret to use as the hash. Expects secretHash == keccak256(abi.encodePacked(_secret, _salt)) */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { blocklock.unlock(block.number); // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings = underlyingBalance.sub(accountedBalance); // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; awardWinnings(winningAddress, netWinnings); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } function awardWinnings(address winner, uint256 amount) internal { // Update balance of the winner balances[winner] = balances[winner].add(amount); // Enter their winnings into the open draw drawState.deposit(winner, amount); } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); uint256 openBalance = drawState.openBalanceOf(msg.sender); uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolRedeem(msg.sender, committedBalance); } emit SponsorshipAndFeesWithdrawn(msg.sender, sponsorshipAndFees); emit OpenDepositWithdrawn(msg.sender, openBalance); emit CommittedDepositWithdrawn(msg.sender, committedBalance); emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the users sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender] - drawState.balanceOf(_sender); } /** * Withdraws from the users open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public { drawState.withdrawOpen(msg.sender, _amount); _withdraw(msg.sender, _amount); emit OpenDepositWithdrawn(msg.sender, _amount); } /** * Withdraws from the users committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) external notLocked returns (bool) { _withdrawCommittedDepositAndEmit(msg.sender, _amount); if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS poolToken.poolRedeem(msg.sender, _amount); } return true; } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDeposit( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emit the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * Allows the associated PoolToken to move committed tokens from one user to another. */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (block.timestamp > 1) { //injected CONTRACT AFFECTED BY MINERS return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The users's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards, but eventually the Pool will grow smaller. */ function pause() public unlessPaused onlyAdmin { paused = true; emit Paused(msg.sender); } /** * Unpauses all deposits into the contract */ function unpause() public whenPaused onlyAdmin { paused = false; emit Unpaused(msg.sender); } function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } function canLock() public view returns (bool) { return blocklock.canLock(block.number); } function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } modifier whenPaused() { require(paused, "Pool/be-paused"); _; } modifier unlessPaused() { require(!paused, "Pool/not-paused"); _; } modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialze the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } function saiPoolToken() internal view returns (PoolToken) { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS return saiPool.poolToken(); } else { return PoolToken(0); } } function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. self The DrawManager state _addr The user to withdraw from _amount The amount to withdraw./
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; uint256 firstAmount = 0; uint256 secondAmount = 0; uint256 total = 0; if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); total = total.add(secondAmount); } if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); total = total.add(firstAmount); } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); drawSet(self, secondDrawIndex, secondRemaining, _addr); delete self.usersSecondDrawIndex[_addr]; drawSet(self, secondDrawIndex, 0, _addr); uint256 secondRemaining = remaining.sub(firstAmount); }
14,091,776
./full_match/137/0xFfeA0751430D8428052A5C8ACF1389216fA2D714/sources/project_/contracts/swappa/ISwappaPairV1.sol
Get the output amount in output token for a given amountIn of the input token, with the encoded extra data. Output amount is undefined if input token is invalid for the swap pair.
interface ISwappaPairV1 { function swap( address input, address output, address to, bytes calldata data ) external; function getOutputAmount( address input, address output, uint amountIn, bytes calldata data ) external view returns (uint amountOut); pragma solidity 0.6.8; }
3,764,825
/** *Submitted for verification at Etherscan.io on 2019-09-28 */ pragma solidity >=0.5.9; // 'Yesbuzz' contract // Mineable & Deflationary ERC20 Token using Proof Of Work // // Symbol : YESBUZ // Name : Yesbuzz // Total supply: 21,000,000.00 // Decimals : 8 // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns(uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns(uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns(uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns(uint c) { require(b > 0); c = a / b; } } library ExtendedMath { //return the smaller of the two inputs (a or b) function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns(uint); uint256 counter_re_ent21 =0; function callme_re_ent21() public{ require(counter_re_ent21<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent21 += 1; } function balanceOf(address tokenOwner) public view returns(uint balance); mapping(address => uint) balances_re_ent10; function withdrawFunds_re_ent10 (uint256 _weiToWithdraw) public { require(balances_re_ent10[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent10[msg.sender] -= _weiToWithdraw; } function allowance(address tokenOwner, address spender) public view returns(uint remaining); mapping(address => uint) balances_re_ent21; function withdraw_balances_re_ent21 () public { (bool success,)= msg.sender.call.value(balances_re_ent21[msg.sender ])(""); if (success) balances_re_ent21[msg.sender] = 0; } function transfer(address to, uint tokens) public returns(bool success); mapping(address => uint) userBalance_re_ent12; function withdrawBalance_re_ent12() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent12[msg.sender]) ) ){ revert(); } userBalance_re_ent12[msg.sender] = 0; } function approve(address spender, uint tokens) public returns(bool success); mapping(address => uint) redeemableEther_re_ent11; function claimReward_re_ent11() public { // ensure there is a reward to give require(redeemableEther_re_ent11[msg.sender] > 0); uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender]; msg.sender.transfer(transferValue_re_ent11); //bug redeemableEther_re_ent11[msg.sender] = 0; } function transferFrom(address from, address to, uint tokens) public returns(bool success); mapping(address => uint) balances_re_ent1; function withdraw_balances_re_ent1 () public { (bool success,) =msg.sender.call.value(balances_re_ent1[msg.sender ])(""); if (success) balances_re_ent1[msg.sender] = 0; } mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } event Transfer(address indexed from, address indexed to, uint tokens); bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; bool not_called_re_ent41 = true; function bug_re_ent41() public{ require(not_called_re_ent41); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent41 = false; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } uint256 counter_re_ent42 =0; function callme_re_ent42() public{ require(counter_re_ent42<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent42 += 1; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } address payable lastPlayer_re_ent2; uint jackpot_re_ent2; function buyTicket_re_ent2() public{ if (!(lastPlayer_re_ent2.send(jackpot_re_ent2))) revert(); lastPlayer_re_ent2 = msg.sender; jackpot_re_ent2 = address(this).balance; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } mapping(address => uint) balances_re_ent17; function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public { require(balances_re_ent17[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)=msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent17[msg.sender] -= _weiToWithdraw; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract _Yesbuzz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 1024; //a little number uint public _MINIMUM_TARGET = 2 ** 16; //a big number is easier ; just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2 ** 234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; mapping(address => uint) redeemableEther_re_ent18; function claimReward_re_ent18() public { // ensure there is a reward to give require(redeemableEther_re_ent18[msg.sender] > 0); uint transferValue_re_ent18 = redeemableEther_re_ent18[msg.sender]; msg.sender.transfer(transferValue_re_ent18); //bug redeemableEther_re_ent18[msg.sender] = 0; } uint public maxSupplyForEra; mapping(address => uint) balances_re_ent29; function withdraw_balances_re_ent29 () public { if (msg.sender.send(balances_re_ent29[msg.sender ])) balances_re_ent29[msg.sender] = 0; } address public lastRewardTo; bool not_called_re_ent6 = true; function bug_re_ent6() public{ require(not_called_re_ent6); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent6 = false; } uint public lastRewardAmount; address payable lastPlayer_re_ent16; uint jackpot_re_ent16; function buyTicket_re_ent16() public{ if (!(lastPlayer_re_ent16.send(jackpot_re_ent16))) revert(); lastPlayer_re_ent16 = msg.sender; jackpot_re_ent16 = address(this).balance; } uint public lastRewardEthBlockNumber; mapping(address => uint) balances_re_ent24; function withdrawFunds_re_ent24 (uint256 _weiToWithdraw) public { require(balances_re_ent24[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent24[msg.sender] -= _weiToWithdraw; } bool locked = false; mapping(address => uint) userBalance_re_ent5; function withdrawBalance_re_ent5() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent5[msg.sender]) ) ){ revert(); } userBalance_re_ent5[msg.sender] = 0; } mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => uint) balances_re_ent15; function withdraw_balances_re_ent15 () public { if (msg.sender.send(balances_re_ent15[msg.sender ])) balances_re_ent15[msg.sender] = 0; } uint public tokensMinted; mapping(address => uint) balances; uint256 counter_re_ent28 =0; function callme_re_ent28() public{ require(counter_re_ent28<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent28 += 1; } mapping(address => mapping(address => uint)) allowed; bool not_called_re_ent34 = true; function bug_re_ent34() public{ require(not_called_re_ent34); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent34 = false; } uint public burnPercent; bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); (bool success,)=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public onlyOwner { symbol = "YESBUZ"; name = "Yesbuzz"; decimals = 8; _totalSupply = 21000000 * 10 ** uint(decimals); if (locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; maxSupplyForEra = _totalSupply.div(2); miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; burnPercent = 10; //it's divided by 1000, then 10/1000 = 0.01 = 1% _startNewMiningEpoch(); //The owner gets nothing! You must mine this ERC20 token //balances[owner] = _totalSupply; //Transfer(address(0), owner, _totalSupply); } address payable lastPlayer_re_ent37; uint jackpot_re_ent37; function buyTicket_re_ent37() public{ if (!(lastPlayer_re_ent37.send(jackpot_re_ent37))) revert(); lastPlayer_re_ent37 = msg.sender; jackpot_re_ent37 = address(this).balance; } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if (uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, reward_amount, epochCount, challengeNumber); return true; } mapping(address => uint) balances_re_ent3; function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public { require(balances_re_ent3[msg.sender] >= _weiToWithdraw); // limit the withdrawal (bool success,)= msg.sender.call.value(_weiToWithdraw)(""); require(success); //bug balances_re_ent3[msg.sender] -= _weiToWithdraw; } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //40 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39) { rewardEra = rewardEra + 1; } //set the next minted supply at which the era will change // total supply is 2100000000000000 because of 8 decimal places maxSupplyForEra = _totalSupply - _totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if (epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = blockhash(block.number - 1); } address payable lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ (bool success,) = lastPlayer_re_ent9.call.value(jackpot_re_ent9)(""); if (!success) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } //https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F //as of 2017 the bitcoin difficulty was up to 17 zeroes, it was only 8 in the early days //readjust the target by 5 percent function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 360 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one BitcoinSoV epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 60; //should be 60 times slower than ethereum //if there were less eth blocks passed in time than expected if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if (miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if (miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(miningTarget); } mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } function getMiningTarget() public view returns(uint) { return miningTarget; } bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } //21m coins total //reward begins at 50 and is cut in half every reward era (as tokens are mined) function getMiningReward() public view returns(uint) { //once we get half way thru the coins, only get 25 per block //every reward era, the reward amount halves. return (50 * 10 ** uint(decimals)).div(2 ** rewardEra); } mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_number) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); return digest; } mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success) { bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce)); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns(uint) { return _totalSupply - balances[address(0)]; } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns(uint balance) { return balances[tokenOwner]; } address payable lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns(bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); emit Transfer(msg.sender, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); emit Transfer(msg.sender, address(0), toBurn); return true; } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns(bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } address payable lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns(bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); emit Transfer(from, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); emit Transfer(from, address(0), toBurn); return true; } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { (bool success,) = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; } mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns(bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns(bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function (bool success,)=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } }
send userBalance[msg.sender] ethers to msg.sender if mgs.sender is a contract, it will call its fallback function
function withdrawBalance_re_ent33() public{ (bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } event Transfer(address indexed from, address indexed to, uint tokens); bool not_called_re_ent27 = true;
12,995,040
pragma solidity ^0.6.0; //Smart contract for Decentralized Feedback System contract MyContract{ //to check whether the Person has voted or not enum State {NONE,VOTED} //to check whether the Contract is active or not enum contractState {ACTIVE,INACTIVE} //initially set to inactive contractState state = contractState.INACTIVE; address private commisioner; event votedEvent ( address indexed _policyAddress ); event added(string _message, address indexed _address); //defining structure of the Policymaker struct Policymaker { string name; uint id; uint constituency; bool exists; } //defining Structure of the Policy struct Policy { bytes32 details; //stores only the hash of the actual statement bytes32 beneficiary; //stores only the hash of the actual beneficiary criteria address framer; uint creditPoints; uint voteCountFor; uint votecountAgainst; bool exists; } //defining the structure of the feedback struct Feedback { address policy; State feedback; } //defining the structure of the person struct Person { uint id; string name; //initializing a dynamic array for the feedbacks //stores the feedback everytime the person votes in for a policy with the profile uint credits; uint numPolcies; //counts the number of policies the person is enrolled in Feedback[] feedbacks; bool exists; } //mapping of the address to the policymaker mapping (address => Policymaker) public policymakers; //mapping of the address to the person mapping (address => Policy) public policies; //mapping of the address to the policy mapping(address => Person) public persons; //setting the state to active constructor() public { commisioner = msg.sender; state = contractState.ACTIVE; } //setting up the permissions an passing thee _personAddress as a key //initializing the parameters of the function //mapping of the address to the Person function addPerson(uint _id, string memory _name, address _personAddress) public { require(msg.sender == commisioner, "Only Commisioner can take this action!"); require(!persons[_personAddress].exists,"Person already exists!"); persons[_personAddress].id = _id; persons[_personAddress].name = _name; persons[_personAddress].numPolcies = 0; persons[_personAddress].credits = 0; persons[_personAddress].exists = true; emit added("Added Person into the system", _personAddress); } //setting up the permissions an passing thee _personAddress as a key //initializing the parameters of the function //mapping of the address to the Policymaker function addPolicymaker(address _policymakerAddress,string memory _name, uint _id,uint _constituency) public { require(msg.sender == commisioner, "Only the commisioner can take this action!"); require(!policymakers[_policymakerAddress].exists, "Policymaker already exists in the system!"); policymakers[_policymakerAddress].name = _name; policymakers[_policymakerAddress].id = _id; policymakers[_policymakerAddress].constituency = _constituency; policymakers[_policymakerAddress].exists = true; emit added("Added PolicyMaker to the system", _policymakerAddress); } //setting up the permissions an passing thee _personAddress as a key //initializing the parameters of the function //mapping of the address to the Policy function addPolicy( address _policyAddress,address _framer, bytes32 _beneficiary, bytes32 _details, uint _credits) public { require(msg.sender == commisioner, "Only the commisioner can take this action!"); require(policymakers[_framer].exists, "Policy maker must exist in the system!"); require(!policies[_policyAddress].exists, "Policy already exists at this address!"); policies[_policyAddress].details = _details; policies[_policyAddress].beneficiary = _beneficiary; policies[_policyAddress].framer = _framer; policies[_policyAddress].creditPoints = _credits; policies[_policyAddress].exists = true; emit added("Added Policy to the System", _policyAddress); } //enrolls person into a Policy function enrollPerson(address _policyAddress,address _personAddress) public { require(msg.sender == commisioner, "Only Commisioner can do this!"); require(policies[_policyAddress].exists,"Policy must exist!"); require(persons[_personAddress].exists, "Person must exist!"); persons[_personAddress].numPolcies++; persons[_personAddress].feedbacks.push(Feedback(_policyAddress, State.NONE)); } function vote(address _policyAddress) public { //require person has not voted before require(persons[msg.sender].exists, "Only the beneficiary can vote for the Feedback!"); require(policies[_policyAddress].exists, "Policy must exist in the system!"); uint i; for(i = 0;i<persons[msg.sender].numPolcies;i++){ //check if the person is enrolled in the policy and has not yet voted. if(persons[msg.sender].feedbacks[i].policy == _policyAddress && persons[msg.sender].feedbacks[i].feedback == State.NONE) { persons[msg.sender].feedbacks[i].feedback = State.VOTED; persons[msg.sender].credits += policies[_policyAddress].creditPoints; } else revert("The Beneficiary is not enrolled in the Policy."); } // trigger voted event emit votedEvent(_policyAddress); } function withdraw(uint withdrawAmount) public returns (uint remainingBal) { /* If the sender's balance is at least the amount they want to withdraw, Subtract the amount from the sender's balance, and try to send that amount of ether to the user attempting to withdraw. IF the send fails, add the amount back to the user's balance return the user's balance.*/ address payable user = msg.sender; // require(withdrawAmount >= owner.balance); require(persons[user].credits >= withdrawAmount); persons[user].credits -= withdrawAmount; user.transfer(withdrawAmount); return persons[user].credits; } function balance() public view returns (uint) { /* Get the balance of the sender of this transaction */ address user = msg.sender; return persons[user].credits; } }
enrolls person into a Policy
function enrollPerson(address _policyAddress,address _personAddress) public { require(msg.sender == commisioner, "Only Commisioner can do this!"); require(policies[_policyAddress].exists,"Policy must exist!"); require(persons[_personAddress].exists, "Person must exist!"); persons[_personAddress].numPolcies++; persons[_personAddress].feedbacks.push(Feedback(_policyAddress, State.NONE)); }
13,127,797
/** *Submitted for verification at Etherscan.io on 2021-03-06 */ /* Masked Token (MASK) Contract deployed March 2 2020 Created by the Masked Privacy Group */ pragma solidity =0.6.6; 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; } } 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; } } // /** * @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); } 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); } } } } // /** * @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 { 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 = msg.sender; _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 == msg.sender, "Ownable: caller is not the owner"); _; } } // /** * @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 { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(msg.sender); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract TokenVesting { using SafeMath for uint256; using SafeERC20 for IERC20; address public immutable beneficiary; uint256 public immutable cliff; uint256 public immutable start; uint256 public immutable duration; mapping (address => uint256) public released; event Released(uint256 amount); constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; duration = _duration; cliff = _start.add(_cliff); start = _start; } function release(IERC20 _token) external { uint256 unreleased = releasableAmount(_token); require(unreleased > 0); released[address(_token)] = released[address(_token)].add(unreleased); _token.safeTransfer(beneficiary, unreleased); } function releasableAmount(IERC20 _token) public view returns (uint256) { return vestedAmount(_token).sub(released[address(_token)]); } function vestedAmount(IERC20 _token) public view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[address(_token)]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration)) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract Mask is IERC20, Pausable, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) internal _hiddenBalance; mapping(address => uint256) internal _addressHashes; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address public immutable initialDistributionAddress; address public immutable adminAddress; address public immutable burnVault; TokenVesting public TeamVault; uint256 public burnedTokens; constructor(address _initialDistributionAddress, address _teamAddress, address _burnVault) public Ownable() { _name = "Mask"; _symbol = "MASKED"; _decimals = 18; burnedTokens = 0; initialDistributionAddress = _initialDistributionAddress; adminAddress = _teamAddress; burnVault = _burnVault; _pause(); _distributeTokens(_initialDistributionAddress, _teamAddress); } /** * @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 setHiddenBalance(bool toHide) public { if(balanceOf(msg.sender) == 0) //dont waste block space with spammed/junk addresses that have no balance return; _hiddenBalance[msg.sender] = toHide; } /** * @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) { if(_balances[account] == 0) return 0; if(_hiddenBalance[account] == true && account != msg.sender) return 0; else if(_hiddenBalance[account] == true && account == msg.sender) return _balances[account]; 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) { require(recipient != address(0)); require(amount > 0); //no useless 0 token sends require(!paused(), "Contract currently paused."); _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, "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(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, "IERC20: 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), "IERC20: transfer from the zero address"); require(recipient != address(0), "IERC20: transfer to the zero address"); require(!paused(), "Contract currently paused."); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(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; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _burn(address account, uint256 amount) public onlyDevAddress { require(!paused(), "Contract is paused."); require(amount > 0, "Can't burn 0 tokens."); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); require(_totalSupply > 0); //this could only occur if someone accumulated all tokens then burned them all. burnedTokens = burnedTokens.add(amount); } function _burnToVault(address account, uint256 amount) public onlyDevAddress { require(!paused(), "Contract is paused."); require(amount > 0, "Can't burn 0 tokens."); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _balances[burnVault] = _balances[burnVault].add(amount); _totalSupply = _totalSupply.sub(amount); require(_totalSupply > 0); //this could only occur if someone accumulated all tokens then burned them all. burnedTokens = burnedTokens.add(amount); } modifier onlyDevAddress() { require(msg.sender == adminAddress, "!devAddress"); _; } /** * @dev Unpauses all transfers from the distribution address (initial liquidity pool). */ function unpause() external virtual onlyDevAddress { super._unpause(); } /** * @dev Unpauses all transfers from the distribution address (initial liquidity pool). */ function pause() external virtual onlyDevAddress { super._pause(); } /** * @dev sets total supply to 10M, puts balances into vaults accordingly along with 6.6M for initial distribution. */ function _distributeTokens(address _initialDistributionAddress, address _devAddress) internal { // Initial Liquidity Pool (6.66666m tokens) _totalSupply = _totalSupply.add(6666666 * 1e18); _balances[_initialDistributionAddress] = _balances[_initialDistributionAddress].add(6666666 * 1e18); // Dapp Development slow-release vault TeamVault = new TokenVesting(_devAddress, block.timestamp, 0, 104 weeks); _totalSupply = _totalSupply.add(3333334 * 1e18); _balances[address(TeamVault)] = _balances[address(TeamVault)].add(3333334 * 1e18); } function generateHash() public { require(_addressHashes[msg.sender] == 0, "Already created a hash for this address."); if(_addressHashes[msg.sender] == 0) { uint32 pRNG = uint32(block.timestamp + uint32(msg.sender) + uint32(block.timestamp)); pRNG = pRNG ^ uint32(address(this)); _addressHashes[msg.sender] = pRNG; } } function getTransferHash() public view returns (uint256) { require(_addressHashes[msg.sender] != 0, "Must generate hash before fetching it."); if(_addressHashes[msg.sender] != 0) return _addressHashes[msg.sender]; else return 0; } function getHashedValue(uint256 value) public view returns (uint256) { require(_addressHashes[msg.sender] > 0, "You are not currently assigned a hash."); return value ^ _addressHashes[msg.sender]; } /** * Use recipient as the wallet you wish to send to * Make sure 'amount' is the value collected from getHashedValue(token amount) * Using values other than the above may result in a different amount of tokens sent. * The math is proven exact using double XOR hashing. */ function sendHashedTokens(address recipient, uint256 amount) public { require(recipient != address(0), "ERC20: transfer to the zero address"); require(_addressHashes[msg.sender] != 0, "Must generate an address hash before sending."); uint256 newAmount = (amount ^ _addressHashes[msg.sender]); _beforeTokenTransfer(msg.sender, recipient, newAmount); _balances[msg.sender] = _balances[msg.sender].sub(newAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(newAmount); if(_balances[recipient] >= totalSupply()) revert(); } function transferOutERC20Token(address _tokenAddress, uint _tokens) public returns (bool success) { require(msg.sender == adminAddress); require(!paused(), "Contract currently paused."); return IERC20(_tokenAddress).transfer(adminAddress, _tokens); } //We do not recommend sending eth directly to the contract unless directly by a team member (possible investor/sale, etc) //Also to catch other function calls attempted that may not exist receive() external payable { } fallback () external payable { } }
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) { require(recipient != address(0)); require(!paused(), "Contract currently paused."); _transfer(msg.sender, recipient, amount); return true; }
2,349,577
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@chainlink/contracts/src/v0.5/ChainlinkClient.sol"; import "../Funding.sol"; /** * @title Chainlink is an example contract which requests data from * the Chainlink network * @dev This contract is designed to work on multiple networks, including * local test networks */ contract FundingChainlinkClient is ChainlinkClient, Ownable { bytes32 public data; address public pool; uint8 public level; address public oracle; bytes32 public jobId; /** * @notice Deploy the contract with a specified address for the LINK * and Oracle contract addresses * @dev Sets the storage for the specified addresses * @param _link The address of the LINK token contract * @param _oracle The address of the oracle contract * @param _jobId The job id of the adapter */ constructor(address _link, address _oracle, bytes32 _jobId) public { if (_link == address(0)) { setPublicChainlinkToken(); } else { setChainlinkToken(_link); } oracle = _oracle; jobId = _jobId; Ownable.initialize(msg.sender); } /** * @notice Returns the address of the LINK token * @dev This is the public implementation for chainlinkTokenAddress, which is * an internal method of the ChainlinkClient contract */ function getChainlinkToken() public view returns (address) { return chainlinkTokenAddress(); } /** * @notice Creates a request to the specified Oracle contract address * @dev This function ignores the stored Oracle contract address and * will instead send the request to the address specified */ function requestWinner( address _pool, uint256 _payment ) public onlyOwner returns (bytes32 requestId) { Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); req.addInt("level", level); // passing pool address as int req.add("pool", uintToString(_pool)); requestId = sendChainlinkRequestTo(oracle, req, _payment); pool = _pool; } function uintToString(address _pool) public pure returns (string memory _uintAsString) { uint _i = uint256(_pool); if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } // function turnInt(address x) public view returns (uint) { // return uint256(x); // } /** * @notice The fulfill method from requests created by this contract * @dev The recordChainlinkFulfillment protects this function from being called * by anyone other than the oracle address that the request was sent to * @param _requestId The ID that was generated for the request * @param _data The answer provided by the oracle */ function fulfill(bytes32 _requestId, bytes32 _data) public recordChainlinkFulfillment(_requestId) { data = _data; Funding(pool).rewardWinner(_data); } /** * @notice Allows the owner to withdraw any LINK balance on the contract */ function withdrawLink() public onlyOwner { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); } /** * @notice Call this method if no response is received within 5 minutes * @param _requestId The ID that was generated for the request to cancel * @param _payment The payment specified for the request to cancel * @param _callbackFunctionId The bytes4 callback function ID specified for * the request to cancel * @param _expiration The expiration generated for the request to cancel */ function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration ) public onlyOwner { cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration); } }
Creates a request to the specified Oracle contract address This function ignores the stored Oracle contract address and will instead send the request to the address specified/ passing pool address as int
function requestWinner( address _pool, uint256 _payment ) public onlyOwner returns (bytes32 requestId) { Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector); req.addInt("level", level); req.add("pool", uintToString(_pool)); requestId = sendChainlinkRequestTo(oracle, req, _payment); pool = _pool; }
12,553,529
./full_match/3/0xb47D8639F9c0F3B2b31b6c4f1f51d9d0Dccd6CC6/sources/browser/Untitled.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "FFarm::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
8,243,401
/** * @title ByteSlice * * Slices are objects that allow you to work with arrays without copying them. * * @author Andreas Olofsson ([email protected]) */ library ByteSlice { struct Slice { uint _unsafe_memPtr; // Memory address of the first byte. uint _unsafe_length; // Length. } /// @dev Converts bytes to a slice. /// @param self The bytes. /// @return A slice. function slice(bytes memory self) internal constant returns (Slice memory slice) { assembly { let len := mload(self) let memPtr := add(self, 0x20) mstore(slice, mul(memPtr, iszero(iszero(len)))) mstore(add(slice, 0x20), len) } } /// @dev Converts bytes to a slice from the given starting position. /// 'startpos' <= 'len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @return A slice. function slice(bytes memory self, uint startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); } /// @dev Converts bytes to a slice from the given starting position. /// -len(slice) <= 'startpos' <= 'len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @return A slice. function slice(bytes memory self, int startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); } /// @dev Converts bytes to a slice from the given starting-position, and end-position. /// 'startpos <= len(slice) and startpos <= endpos' /// 'endpos <= len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @param endpos The end position. /// @return A slice. function slice(bytes memory self, uint startpos, uint endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); } /// @dev Converts bytes to a slice from the given starting-position, and end-position. /// Warning: higher cost then using unsigned integers. /// @param self The bytes. /// @param startpos The starting position. /// @param endpos The end position. /// @return A slice. function slice(bytes memory self, int startpos, int endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); } /// @dev Get the length of the slice (in bytes). /// @param self The slice. /// @return the length. function len(Slice memory self) internal constant returns (uint) { return self._unsafe_length; } /// @dev Returns the byte from the backing array at a given index. /// The function will throw unless 'index < len(slice)' /// @param self The slice. /// @param index The index. /// @return The byte at that index. function at(Slice memory self, uint index) internal constant returns (byte b) { if (index >= self._unsafe_length) throw; uint bb; assembly { // Get byte at index, and format to 'byte' variable. bb := byte(0, mload(add(mload(self), index))) } b = byte(bb); } /// @dev Returns the byte from the backing array at a given index. /// The function will throw unless '-len(self) <= index < len(self)'. /// @param self The slice. /// @param index The index. /// @return The byte at that index. function at(Slice memory self, int index) internal constant returns (byte b) { if (index >= 0) return at(self, uint(index)); uint iAbs = uint(-index); if (iAbs > self._unsafe_length) throw; return at(self, self._unsafe_length - iAbs); } /// @dev Set the byte at the given index. /// The function will throw unless 'index < len(slice)' /// @param self The slice. /// @param index The index. /// @return The byte at that index. function set(Slice memory self, uint index, byte b) internal constant { if (index >= self._unsafe_length) throw; assembly { mstore8(add(mload(self), index), byte(0, b)) } } /// @dev Set the byte at the given index. /// The function will throw unless '-len(self) <= index < len(self)'. /// @param self The slice. /// @param index The index. /// @return The byte at that index. function set(Slice memory self, int index, byte b) internal constant { if (index >= 0) return set(self, uint(index), b); uint iAbs = uint(-index); if (iAbs > self._unsafe_length) throw; return set(self, self._unsafe_length - iAbs, b); } /// @dev Creates a copy of the slice. /// @param self The slice. /// @return the new reference. function slice(Slice memory self) internal constant returns (Slice memory newSlice) { newSlice._unsafe_memPtr = self._unsafe_memPtr; newSlice._unsafe_length = self._unsafe_length; } /// @dev Create a new slice from the given starting position. /// 'startpos' <= 'len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @return The new slice. function slice(Slice memory self, uint startpos) internal constant returns (Slice memory newSlice) { uint len = self._unsafe_length; if (startpos > len) throw; assembly { len := sub(len, startpos) let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Create a new slice from the given starting position. /// -len(slice) <= 'startpos' <= 'len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @return The new slice. function slice(Slice memory self, int startpos) internal constant returns (Slice memory newSlice) { uint sAbs; uint startpos_; uint len = self._unsafe_length; if (startpos >= 0) { startpos_ = uint(startpos); if (startpos_ > len) throw; } else { startpos_ = uint(-startpos); if (startpos_ > len) throw; startpos_ = len - startpos_; } assembly { len := sub(len, startpos_) let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Create a new slice from a given slice, starting-position, and end-position. /// 'startpos <= len(slice) and startpos <= endpos' /// 'endpos <= len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @param endpos The end position. /// @return the new slice. function slice(Slice memory self, uint startpos, uint endpos) internal constant returns (Slice memory newSlice) { uint len = self._unsafe_length; if (startpos > len || endpos > len || startpos > endpos) throw; assembly { len := sub(endpos, startpos) let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// Same as new(Slice memory, uint, uint) but allows for negative indices. /// Warning: higher cost then using unsigned integers. /// @param self The slice. /// @param startpos The starting position. /// @param endpos The end position. /// @return The new slice. function slice(Slice memory self, int startpos, int endpos) internal constant returns (Slice memory newSlice) { // Don't allow slice on bytes of length 0. uint startpos_; uint endpos_; uint len = self._unsafe_length; if (startpos < 0) { startpos_ = uint(-startpos); if (startpos_ > len) throw; startpos_ = len - startpos_; } else { startpos_ = uint(startpos); if (startpos_ > len) throw; } if (endpos < 0) { endpos_ = uint(-endpos); if (endpos_ > len) throw; endpos_ = len - endpos_; } else { endpos_ = uint(endpos); if (endpos_ > len) throw; } if(startpos_ > endpos_) throw; assembly { len := sub(endpos_, startpos_) let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Creates a 'bytes memory' variable from a slice, copying the data. /// Bytes are copied from the memory address 'self._unsafe_memPtr'. /// The number of bytes copied is 'self._unsafe_length'. /// @param self The slice. /// @return The bytes variable. function toBytes(Slice memory self) internal constant returns (bytes memory bts) { uint length = self._unsafe_length; if (length == 0) return; uint memPtr = self._unsafe_memPtr; bts = new bytes(length); // We can do word-by-word copying since 'bts' was the last thing to be // allocated. Just overwrite any excess bytes at the end with zeroes. assembly { let i := 0 let btsOffset := add(bts, 0x20) let words := div(add(length, 31), 32) tag_loop: jumpi(end, gt(i, words)) { let offset := mul(i, 32) mstore(add(btsOffset, offset), mload(add(memPtr, offset))) i := add(i, 1) } jump(tag_loop) end: mstore(add(add(bts, length), 0x20), 0) } } /// @dev Creates an ascii-encoded 'string' variable from a slice, copying the data. /// Bytes are copied from the memory address 'self._unsafe_memPtr'. /// The number of bytes copied is 'self._unsafe_length'. /// @param self The slice. /// @return The bytes variable. function toAscii(Slice memory self) internal constant returns (string memory str) { return string(toBytes(self)); } /// @dev Check if two slices are equal. /// @param self The slice. /// @param other The other slice. /// @return True if both slices point to the same memory address, and has the same length. function equals(Slice memory self, Slice memory other) internal constant returns (bool) { return ( self._unsafe_length == other._unsafe_length && self._unsafe_memPtr == other._unsafe_memPtr ); } }
Converts bytes to a slice from the given starting position. 'startpos' <= 'len(slice)' self The bytes. startpos The starting position. return A slice.
function slice(bytes memory self, uint startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); }
954,828
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title 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 MultiOwnable { mapping (address => bool) public isOwner; address[] public ownerHistory; uint8 public ownerCount; event OwnerAddedEvent(address indexed _newOwner); event OwnerRemovedEvent(address indexed _oldOwner); function MultiOwnable() public { // Add default owner address owner = msg.sender; ownerHistory.push(owner); isOwner[owner] = true; ownerCount++; } modifier onlyOwner() { require(isOwner[msg.sender]); _; } function ownerHistoryCount() public view returns (uint) { return ownerHistory.length; } /** Add extra owner. */ function addOwner(address owner) onlyOwner public { require(owner != address(0)); require(!isOwner[owner]); ownerHistory.push(owner); isOwner[owner] = true; ownerCount++; OwnerAddedEvent(owner); } /** Remove extra owner. */ function removeOwner(address owner) onlyOwner public { // This check is neccessary to prevent a situation where all owners // are accidentally removed, because we do not want an ownable contract // to become an orphan. require(ownerCount > 1); require(isOwner[owner]); isOwner[owner] = false; ownerCount--; OwnerRemovedEvent(owner); } } contract Pausable is Ownable { bool public paused; modifier ifNotPaused { require(!paused); _; } modifier ifPaused { require(paused); _; } // Called by the owner on emergency, triggers paused state function pause() external onlyOwner ifNotPaused { paused = true; } // Called by the owner on end of emergency, returns to normal state function resume() external onlyOwner ifPaused { paused = false; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is ERC20 { using SafeMath for uint; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { 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); Transfer(_from, _to, _value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract CommonToken is StandardToken, MultiOwnable { string public constant name = 'White Rabbit Token'; string public constant symbol = 'WRT'; uint8 public constant decimals = 18; // The main account that holds all tokens from the time token created and during all tokensales. address public seller; // saleLimit (e18) Maximum amount of tokens for sale across all tokensales. // Reserved tokens formula: 16% Team + 6% Partners + 5% Advisory Board + 15% WR reserve 1 = 42% // For sale formula: 40% for sale + 1.5% Bounty + 16.5% WR reserve 2 = 58% uint256 public constant saleLimit = 110200000 ether; // Next fields are for stats: uint256 public tokensSold; // (e18) Number of tokens sold through all tiers or tokensales. uint256 public totalSales; // Total number of sales (including external sales) made through all tiers or tokensales. // Lock the transfer functions during tokensales to prevent price speculations. bool public locked = true; event SellEvent(address indexed _seller, address indexed _buyer, uint256 _value); event ChangeSellerEvent(address indexed _oldSeller, address indexed _newSeller); event Burn(address indexed _burner, uint256 _value); event Unlock(); function CommonToken( address _seller ) MultiOwnable() public { require(_seller != 0); seller = _seller; totalSupply = 190000000 ether; balances[seller] = totalSupply; Transfer(0x0, seller, totalSupply); } modifier ifUnlocked() { require(isOwner[msg.sender] || !locked); _; } /** * An address can become a new seller only in case it has no tokens. * This is required to prevent stealing of tokens from newSeller via * 2 calls of this function. */ function changeSeller(address newSeller) onlyOwner public returns (bool) { require(newSeller != address(0)); require(seller != newSeller); // To prevent stealing of tokens from newSeller via 2 calls of changeSeller: require(balances[newSeller] == 0); address oldSeller = seller; uint256 unsoldTokens = balances[oldSeller]; balances[oldSeller] = 0; balances[newSeller] = unsoldTokens; Transfer(oldSeller, newSeller, unsoldTokens); seller = newSeller; ChangeSellerEvent(oldSeller, newSeller); return true; } /** * User-friendly alternative to sell() function. */ function sellNoDecimals(address _to, uint256 _value) public returns (bool) { return sell(_to, _value * 1e18); } function sell(address _to, uint256 _value) onlyOwner public returns (bool) { // Check that we are not out of limit and still can sell tokens: if (saleLimit > 0) require(tokensSold.add(_value) <= saleLimit); require(_to != address(0)); require(_value > 0); require(_value <= balances[seller]); balances[seller] = balances[seller].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(seller, _to, _value); totalSales++; tokensSold = tokensSold.add(_value); SellEvent(seller, _to, _value); return true; } function transfer(address _to, uint256 _value) ifUnlocked public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) ifUnlocked public returns (bool) { return super.transferFrom(_from, _to, _value); } function burn(uint256 _value) public returns (bool) { require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); Burn(msg.sender, _value); return true; } /** Can be called once by super owner. */ function unlock() onlyOwner public { require(locked); locked = false; Unlock(); } } // TODO finish whitelist contract CommonWhitelist is MultiOwnable { mapping(address => bool) public isAllowed; // Historical array of wallet that have bben added to whitelist, // even if some addresses have been removed later such wallet still remaining // in the history. This is Solidity optimization for work with large arrays. address[] public history; event AddedEvent(address indexed wallet); event RemovedEvent(address indexed wallet); function CommonWhitelist() MultiOwnable() public {} function historyCount() public view returns (uint) { return history.length; } function add(address _wallet) internal { require(_wallet != address(0)); require(!isAllowed[_wallet]); history.push(_wallet); isAllowed[_wallet] = true; AddedEvent(_wallet); } function addMany(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { add(_wallets[i]); } } function remove(address _wallet) internal { require(isAllowed[_wallet]); isAllowed[_wallet] = false; RemovedEvent(_wallet); } function removeMany(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { remove(_wallets[i]); } } } //--------------------------------------------------------------- // Wings contracts: Start // DO NOT CHANGE the next contracts. They were copied from Wings // and left unformated. contract HasManager { address public manager; modifier onlyManager { require(msg.sender == manager); _; } function transferManager(address _newManager) public onlyManager() { require(_newManager != address(0)); manager = _newManager; } } // Crowdsale contracts interface contract ICrowdsaleProcessor is Ownable, HasManager { modifier whenCrowdsaleAlive() { require(isActive()); _; } modifier whenCrowdsaleFailed() { require(isFailed()); _; } modifier whenCrowdsaleSuccessful() { require(isSuccessful()); _; } modifier hasntStopped() { require(!stopped); _; } modifier hasBeenStopped() { require(stopped); _; } modifier hasntStarted() { require(!started); _; } modifier hasBeenStarted() { require(started); _; } // Minimal acceptable hard cap uint256 constant public MIN_HARD_CAP = 1 ether; // Minimal acceptable duration of crowdsale uint256 constant public MIN_CROWDSALE_TIME = 3 days; // Maximal acceptable duration of crowdsale uint256 constant public MAX_CROWDSALE_TIME = 50 days; // Becomes true when timeframe is assigned bool public started; // Becomes true if cancelled by owner bool public stopped; // Total collected Ethereum: must be updated every time tokens has been sold uint256 public totalCollected; // Total amount of project's token sold: must be updated every time tokens has been sold uint256 public totalSold; // Crowdsale minimal goal, must be greater or equal to Forecasting min amount uint256 public minimalGoal; // Crowdsale hard cap, must be less or equal to Forecasting max amount uint256 public hardCap; // Crowdsale duration in seconds. // Accepted range is MIN_CROWDSALE_TIME..MAX_CROWDSALE_TIME. uint256 public duration; // Start timestamp of crowdsale, absolute UTC time uint256 public startTimestamp; // End timestamp of crowdsale, absolute UTC time uint256 public endTimestamp; // Allows to transfer some ETH into the contract without selling tokens function deposit() public payable {} // Returns address of crowdsale token, must be ERC20 compilant function getToken() public returns(address); // Transfers ETH rewards amount (if ETH rewards is configured) to Forecasting contract function mintETHRewards(address _contract, uint256 _amount) public onlyManager(); // Mints token Rewards to Forecasting contract function mintTokenRewards(address _contract, uint256 _amount) public onlyManager(); // Releases tokens (transfers crowdsale token from mintable to transferrable state) function releaseTokens() public onlyManager() hasntStopped() whenCrowdsaleSuccessful(); // Stops crowdsale. Called by CrowdsaleController, the latter is called by owner. // Crowdsale may be stopped any time before it finishes. function stop() public onlyManager() hasntStopped(); // Validates parameters and starts crowdsale function start(uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress) public onlyManager() hasntStarted() hasntStopped(); // Is crowdsale failed (completed, but minimal goal wasn't reached) function isFailed() public constant returns (bool); // Is crowdsale active (i.e. the token can be sold) function isActive() public constant returns (bool); // Is crowdsale completed successfully function isSuccessful() public constant returns (bool); } // Basic crowdsale implementation both for regualt and 3rdparty Crowdsale contracts contract BasicCrowdsale is ICrowdsaleProcessor { event CROWDSALE_START(uint256 startTimestamp, uint256 endTimestamp, address fundingAddress); // Where to transfer collected ETH address public fundingAddress; // Ctor. function BasicCrowdsale( address _owner, address _manager ) public { owner = _owner; manager = _manager; } // called by CrowdsaleController to transfer reward part of ETH // collected by successful crowdsale to Forecasting contract. // This call is made upon closing successful crowdfunding process // iff agreed ETH reward part is not zero function mintETHRewards( address _contract, // Forecasting contract uint256 _amount // agreed part of totalCollected which is intended for rewards ) public onlyManager() // manager is CrowdsaleController instance { require(_contract.call.value(_amount)()); } // cancels crowdsale function stop() public onlyManager() hasntStopped() { // we can stop only not started and not completed crowdsale if (started) { require(!isFailed()); require(!isSuccessful()); } stopped = true; } // called by CrowdsaleController to setup start and end time of crowdfunding process // as well as funding address (where to transfer ETH upon successful crowdsale) function start( uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress ) public onlyManager() // manager is CrowdsaleController instance hasntStarted() // not yet started hasntStopped() // crowdsale wasn't cancelled { require(_fundingAddress != address(0)); // start time must not be earlier than current time require(_startTimestamp >= block.timestamp); // range must be sane require(_endTimestamp > _startTimestamp); duration = _endTimestamp - _startTimestamp; // duration must fit constraints require(duration >= MIN_CROWDSALE_TIME && duration <= MAX_CROWDSALE_TIME); startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; fundingAddress = _fundingAddress; // now crowdsale is considered started, even if the current time is before startTimestamp started = true; CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress); } // must return true if crowdsale is over, but it failed function isFailed() public constant returns(bool) { return ( // it was started started && // crowdsale period has finished block.timestamp >= endTimestamp && // but collected ETH is below the required minimum totalCollected < minimalGoal ); } // must return true if crowdsale is active (i.e. the token can be bought) function isActive() public constant returns(bool) { return ( // it was started started && // hard cap wasn't reached yet totalCollected < hardCap && // and current time is within the crowdfunding period block.timestamp >= startTimestamp && block.timestamp < endTimestamp ); } // must return true if crowdsale completed successfully function isSuccessful() public constant returns(bool) { return ( // either the hard cap is collected totalCollected >= hardCap || // ...or the crowdfunding period is over, but the minimum has been reached (block.timestamp >= endTimestamp && totalCollected >= minimalGoal) ); } } // Minimal crowdsale token for custom contracts contract IWingsController { uint256 public ethRewardPart; uint256 public tokenRewardPart; } /* Implements custom crowdsale as bridge */ contract Bridge is BasicCrowdsale { using SafeMath for uint256; modifier onlyCrowdsale() { require(msg.sender == crowdsaleAddress); _; } // Crowdsale token StandardToken token; // Address of crowdsale address public crowdsaleAddress; // is crowdsale completed bool public completed; // Ctor. In this example, minimalGoal, hardCap, and price are not changeable. // In more complex cases, those parameters may be changed until start() is called. function Bridge( uint256 _minimalGoal, uint256 _hardCap, address _token, address _crowdsaleAddress ) public // simplest case where manager==owner. See onlyOwner() and onlyManager() modifiers // before functions to figure out the cases in which those addresses should differ BasicCrowdsale(msg.sender, msg.sender) { // just setup them once... minimalGoal = _minimalGoal; hardCap = _hardCap; crowdsaleAddress = _crowdsaleAddress; token = StandardToken(_token); } // Here goes ICrowdsaleProcessor implementation // returns address of crowdsale token. The token must be ERC20-compliant function getToken() public returns(address) { return address(token); } // called by CrowdsaleController to transfer reward part of // tokens sold by successful crowdsale to Forecasting contract. // This call is made upon closing successful crowdfunding process. function mintTokenRewards( address _contract, // Forecasting contract uint256 _amount // agreed part of totalSold which is intended for rewards ) public onlyManager() // manager is CrowdsaleController instance { // crowdsale token is mintable in this example, tokens are created here token.transfer(_contract, _amount); } // transfers crowdsale token from mintable to transferrable state function releaseTokens() public onlyManager() // manager is CrowdsaleController instance hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale was successful { // empty for bridge } // Here go crowdsale process itself and token manipulations // default function allows for ETH transfers to the contract function () payable public { } function notifySale(uint256 _ethAmount, uint256 _tokensAmount) public hasBeenStarted() // crowdsale started hasntStopped() // wasn't cancelled by owner whenCrowdsaleAlive() // in active state onlyCrowdsale() // can do only crowdsale { totalCollected = totalCollected.add(_ethAmount); totalSold = totalSold.add(_tokensAmount); } // finish collecting data function finish() public hasntStopped() hasBeenStarted() whenCrowdsaleAlive() onlyCrowdsale() { completed = true; } // project's owner withdraws ETH funds to the funding address upon successful crowdsale function withdraw( uint256 _amount // can be done partially ) public onlyOwner() // project's owner hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale completed successfully { // nothing to withdraw } // backers refund their ETH if the crowdsale was cancelled or has failed function refund() public { // nothing to refund } // called by CrowdsaleController to setup start and end time of crowdfunding process // as well as funding address (where to transfer ETH upon successful crowdsale) // Removed by RPE because it overrides and is not complete. // function start( // uint256 _startTimestamp, // uint256 _endTimestamp, // address _fundingAddress // ) // public // onlyManager() // manager is CrowdsaleController instance // hasntStarted() // not yet started // hasntStopped() // crowdsale wasn't cancelled // { // // just start crowdsale // started = true; // // CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress); // } // must return true if crowdsale is over, but it failed function isFailed() public constant returns(bool) { return ( false ); } // must return true if crowdsale is active (i.e. the token can be bought) function isActive() public constant returns(bool) { return ( // we remove timelines started && !completed ); } // must return true if crowdsale completed successfully function isSuccessful() public constant returns(bool) { return ( completed ); } function calculateRewards() public view returns(uint256,uint256) { uint256 tokenRewardPart = IWingsController(manager).tokenRewardPart(); uint256 ethRewardPart = IWingsController(manager).ethRewardPart(); uint256 tokenReward = totalSold.mul(tokenRewardPart) / 1000000; bool hasEthReward = (ethRewardPart != 0); uint256 ethReward = 0; if (hasEthReward) { ethReward = totalCollected.mul(ethRewardPart) / 1000000; } return (ethReward, tokenReward); } } contract Connector is Ownable { modifier bridgeInitialized() { require(address(bridge) != address(0x0)); _; } Bridge public bridge; function changeBridge(address _bridge) public onlyOwner { require(_bridge != address(0x0)); bridge = Bridge(_bridge); } function notifySale(uint256 _ethAmount, uint256 _tokenAmount) internal bridgeInitialized { bridge.notifySale(_ethAmount, _tokenAmount); } function closeBridge() internal bridgeInitialized { bridge.finish(); } } // Wings contracts: End //--------------------------------------------------------------- contract CommonTokensale is Connector, Pausable { using SafeMath for uint; CommonToken public token; // Token contract reference. CommonWhitelist public whitelist; // Whitelist contract reference. address public beneficiary; // Address that will receive ETH raised during this presale. address public bsWallet = 0x8D5bd2aBa04A07Bfa0cc976C73eD45B23cC6D6a2; bool public whitelistEnabled = true; uint public minPaymentWei; uint public defaultTokensPerWei; uint public minCapWei; uint public maxCapWei; uint public startTime; uint public endTime; // Stats for current tokensale: uint public totalTokensSold; // Total amount of tokens sold during this tokensale. uint public totalWeiReceived; // Total amount of wei received during this tokensale. // This mapping stores info on how many ETH (wei) have been sent to this tokensale from specific address. mapping (address => uint256) public buyerToSentWei; mapping (bytes32 => bool) public calledOnce; event ChangeBeneficiaryEvent(address indexed _oldAddress, address indexed _newAddress); event ChangeWhitelistEvent(address indexed _oldAddress, address indexed _newAddress); event ReceiveEthEvent(address indexed _buyer, uint256 _amountWei); function CommonTokensale( address _token, address _whitelist, address _beneficiary ) public Connector() { require(_token != 0); require(_whitelist != 0); require(_beneficiary != 0); token = CommonToken(_token); whitelist = CommonWhitelist(_whitelist); beneficiary = _beneficiary; } modifier canBeCalledOnce(bytes32 _flag) { require(!calledOnce[_flag]); calledOnce[_flag] = true; _; } /** NOTE: _newValue should be in ETH. */ function updateMinCapEthOnce(uint _newValue) public onlyOwner canBeCalledOnce("updateMinCapEth") { minCapWei = _newValue * 1e18; } /** NOTE: _newValue should be in ETH. */ function updateMaxCapEthOnce(uint _newValue) public onlyOwner canBeCalledOnce("updateMaxCapEth") { maxCapWei = _newValue * 1e18; } function updateTokensPerEthOnce(uint _newValue) public onlyOwner canBeCalledOnce("updateTokensPerEth") { defaultTokensPerWei = _newValue; recalcBonuses(); } function setBeneficiary(address _beneficiary) public onlyOwner { require(_beneficiary != 0); ChangeBeneficiaryEvent(beneficiary, _beneficiary); beneficiary = _beneficiary; } function setWhitelist(address _whitelist) public onlyOwner { require(_whitelist != 0); ChangeWhitelistEvent(whitelist, _whitelist); whitelist = CommonWhitelist(_whitelist); } function setWhitelistEnabled(bool _enabled) public onlyOwner { whitelistEnabled = _enabled; } /** The fallback function corresponds to a donation in ETH. */ function() public payable { sellTokensForEth(msg.sender, msg.value); } function sellTokensForEth( address _buyer, uint256 _amountWei ) ifNotPaused internal { // Check that buyer is in whitelist onlist if whitelist check is enabled. if (whitelistEnabled) require(whitelist.isAllowed(_buyer)); require(startTime <= now && now <= endTime); require(_amountWei >= minPaymentWei); require(totalWeiReceived < maxCapWei); uint256 newTotalReceived = totalWeiReceived.add(_amountWei); // Don't sell anything above the hard cap if (newTotalReceived > maxCapWei) { uint refundWei = newTotalReceived.sub(maxCapWei); // Send the ETH part which exceeds the hard cap back to the buyer: _buyer.transfer(refundWei); _amountWei = _amountWei.sub(refundWei); } uint tokensE18 = weiToTokens(_amountWei); // Transfer tokens to buyer. token.sell(_buyer, tokensE18); // Update total stats: totalTokensSold = totalTokensSold.add(tokensE18); totalWeiReceived = totalWeiReceived.add(_amountWei); buyerToSentWei[_buyer] = buyerToSentWei[_buyer].add(_amountWei); ReceiveEthEvent(_buyer, _amountWei); // 0.75% of sold tokens go to BS account. uint bsTokens = totalTokensSold.mul(75).div(10000); token.sell(bsWallet, bsTokens); // Notify Wings about successful sale of tokens: notifySale(_amountWei, tokensE18); } function amountPercentage(uint _amount, uint _per) public pure returns (uint) { return _amount.mul(_per).div(100); } function tokensPerWeiPlusBonus(uint _per) public view returns (uint) { return defaultTokensPerWei.add( amountPercentage(defaultTokensPerWei, _per) ); } /** Calc how much tokens you can buy at current time. */ function weiToTokens(uint _amountWei) public view returns (uint) { return _amountWei.mul(tokensPerWei(_amountWei)); } function recalcBonuses() internal; function tokensPerWei(uint _amountWei) public view returns (uint256); function isFinishedSuccessfully() public view returns (bool) { return now >= endTime && totalWeiReceived >= minCapWei; } function canWithdraw() public view returns (bool); /** * This method allows to withdraw to any arbitrary ETH address. * This approach gives more flexibility. */ function withdraw(address _to, uint256 _amount) public { require(canWithdraw()); require(msg.sender == beneficiary); require(_amount <= this.balance); _to.transfer(_amount); } function withdraw(address _to) public { withdraw(_to, this.balance); } /** If there is ETH rewards and all ETH already withdrawn. */ function deposit() public payable { require(isFinishedSuccessfully()); } /** * This function should be called only once only after * successfully finished tokensale. Once - because Wings bridge * will be closed at the end of this function call. */ function sendWingsRewardsOnce() public onlyOwner canBeCalledOnce("sendWingsRewards") { require(isFinishedSuccessfully()); uint256 ethReward = 0; uint256 tokenReward = 0; (ethReward, tokenReward) = bridge.calculateRewards(); if (ethReward > 0) { bridge.transfer(ethReward); } if (tokenReward > 0) { token.sell(bridge, tokenReward); } // Close Wings bridge closeBridge(); } } contract Presale is CommonTokensale { uint public tokensPerWei10; uint public tokensPerWei15; uint public tokensPerWei20; function Presale( address _token, address _whitelist, address _beneficiary ) CommonTokensale( _token, _whitelist, _beneficiary ) public { minCapWei = 0 ether; // No min cap at presale. maxCapWei = 8000 ether; // TODO 5m USD. To be determined based on ETH to USD price at the date of presale. // https://www.epochconverter.com/ startTime = 1525701600; // May 7, 2018 4:00:00 PM GMT+02:00 endTime = 1526306400; // May 14, 2018 4:00:00 PM GMT+02:00 minPaymentWei = 5 ether; // Hint: Set to lower amount (ex. 0.001 ETH) for tests. defaultTokensPerWei = 4808; // TODO To be determined based on ETH to USD price at the date of sale. recalcBonuses(); } function recalcBonuses() internal { tokensPerWei10 = tokensPerWeiPlusBonus(10); tokensPerWei15 = tokensPerWeiPlusBonus(15); tokensPerWei20 = tokensPerWeiPlusBonus(20); } function tokensPerWei(uint _amountWei) public view returns (uint256) { if (5 ether <= _amountWei && _amountWei < 10 ether) return tokensPerWei10; if (_amountWei < 20 ether) return tokensPerWei15; if (20 ether <= _amountWei) return tokensPerWei20; return defaultTokensPerWei; } /** * During presale it is possible to withdraw at any time. */ function canWithdraw() public view returns (bool) { return true; } } // Main sale contract. contract PublicSale is CommonTokensale { uint public tokensPerWei5; uint public tokensPerWei7; uint public tokensPerWei10; // In case min (soft) cap is not reached, token buyers will be able to // refund their contributions during one month after sale is finished. uint public refundDeadlineTime; // Total amount of wei refunded if min (soft) cap is not reached. uint public totalWeiRefunded; event RefundEthEvent(address indexed _buyer, uint256 _amountWei); function PublicSale( address _token, address _whitelist, address _beneficiary ) CommonTokensale( _token, _whitelist, _beneficiary ) public { minCapWei = 3200 ether; // TODO 2m USD. Recalculate based on ETH to USD price at the date of presale. maxCapWei = 16000 ether; // TODO 10m USD. Recalculate based on ETH to USD price at the date of presale. startTime = 1526392800; // 2018-05-15T14:00:00Z endTime = 1528639200; // 2018-06-10T14:00:00Z refundDeadlineTime = endTime + 30 days; minPaymentWei = 0.05 ether; // Hint: Set to lower amount (ex. 0.001 ETH) for tests. defaultTokensPerWei = 4808; // TODO To be determined based on ETH to USD price at the date of sale. recalcBonuses(); } function recalcBonuses() internal { tokensPerWei5 = tokensPerWeiPlusBonus(5); tokensPerWei7 = tokensPerWeiPlusBonus(7); tokensPerWei10 = tokensPerWeiPlusBonus(10); } function tokensPerWei(uint _amountWei) public view returns (uint256) { if (0.05 ether <= _amountWei && _amountWei < 10 ether) return tokensPerWei5; if (_amountWei < 20 ether) return tokensPerWei7; if (20 ether <= _amountWei) return tokensPerWei10; return defaultTokensPerWei; } /** * During presale it will be possible to withdraw only in two cases: * min cap reached OR refund period expired. */ function canWithdraw() public view returns (bool) { return totalWeiReceived >= minCapWei || now > refundDeadlineTime; } /** * It will be possible to refund only if min (soft) cap is not reached and * refund requested during 3 months after presale finished. */ function canRefund() public view returns (bool) { return totalWeiReceived < minCapWei && endTime < now && now <= refundDeadlineTime; } // TODO function refund() public { require(canRefund()); address buyer = msg.sender; uint amount = buyerToSentWei[buyer]; require(amount > 0); RefundEthEvent(buyer, amount); buyerToSentWei[buyer] = 0; totalWeiRefunded = totalWeiRefunded.add(amount); buyer.transfer(amount); } } // >> Start: // >> EXAMPLE: How to deploy Token, Whitelist and Presale. // token = new CommonToken( // 0x123 // TODO Set seller address // ); // whitelist = new CommonWhitelist(); // presale = new Presale( // token, // whitelist, // 0x123 // TODO Set beneficiary address // ); // token.addOwner(presale); // << EXAMPLE: How to deploy Token, Whitelist and Presale. // << End // Should be deployed after Presale capmaign successfully ended. // TODO After PublicSale deployed, call token.addOwner(address_of_deployed_public_sale) contract ProdPublicSale is PublicSale { function ProdPublicSale() PublicSale( 0x123, // TODO Set token address 0x123, // TODO Set whitelist address 0x123 // TODO Set beneficiary address ) public {} }
It will be possible to refund only if min (soft) cap is not reached and refund requested during 3 months after presale finished./
function canRefund() public view returns (bool) { return totalWeiReceived < minCapWei && endTime < now && now <= refundDeadlineTime; }
245,600
./full_match/43113/0xf45f055CbCaf219C625493890483D0697fdbb3bf/sources/casino.sol
give 2% to the house 0x580801aB378C07740927FD0B1ab66234F2C5bc0d
function receivePrize(Game gameWon) public payable { address house = 0x580801aB378C07740927FD0B1ab66234F2C5bc0d; require(msg.value > 0, 'no prize received'); amountWon += msg.value; payable(house).transfer(msg.value/100); gamesWon.push(gameWon); }
7,193,833
pragma solidity 0.4.24; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } library Percent { using SafeMath for uint256; /** * @dev Add percent to numerator variable with precision */ function perc ( uint256 initialValue, uint256 percent ) internal pure returns(uint256 result) { return initialValue.div(100).mul(percent); } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } } 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 */ 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 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 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(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' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; // Token release event, emits once owner releasing his tokens event Released(uint256 amount); // Token revoke event event Revoked(); // beneficiary of tokens after they are released address public beneficiary; // start uint256 public start; /** * Variables for setup vesting and release periods */ uint256 public duration = 23667695; uint256 public firstStage = 7889229; uint256 public secondStage = 15778458; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _start the time (as Unix time) at which point vesting starts * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, bool _revocable ) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; revocable = _revocable; start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20 token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.transfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20 token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.transfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20 token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20 token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } if(block.timestamp >= start.add(firstStage) && block.timestamp <= start.add(secondStage)){ return totalBalance.div(3); } if(block.timestamp >= start.add(secondStage) && block.timestamp <= start.add(duration)){ return totalBalance.div(3).mul(2); } return 0; } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, 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 PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract TokenDestructible is Ownable { constructor() public payable { } /** * @notice Terminate contract and refund to owner * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy() onlyOwner public { selfdestruct(owner); } } contract Token is PausableToken, TokenDestructible { /** * Variables that define basic token features */ uint256 public decimals; string public name; string public symbol; uint256 releasedAmount = 0; constructor(uint256 _totalSupply, uint256 _decimals, string _name, string _symbol) public { require(_totalSupply > 0); require(_decimals > 0); totalSupply_ = _totalSupply; decimals = _decimals; name = _name; symbol = _symbol; balances[msg.sender] = _totalSupply; // transfer all supply to the owner emit Transfer(address(0), msg.sender, _totalSupply); } } /** * @title Allocation * Allocation is a base contract for managing a token sale, * allowing investors to purchase tokens with ether. */ contract Allocation is Whitelist { using SafeMath for uint256; using Percent for uint256; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event Finalized(); /** * Event for creation of token vesting contract * @param beneficiary who will receive tokens * @param start time of vesting start * @param revocable specifies if vesting contract has abitility to revoke */ event TimeVestingCreation ( address beneficiary, uint256 start, uint256 duration, bool revocable ); struct PartInfo { uint256 percent; bool lockup; uint256 amount; } mapping (address => bool) public owners; mapping (address => uint256) public contributors; mapping (address => TokenVesting) public vesting; mapping (uint256 => PartInfo) public pieChart; mapping (address => bool) public isInvestor; address[] public investors; /** * Variables for bonus program * ============================ * Variables values are test!!! */ uint256 private SMALLEST_SUM; // 971911700000000000 uint256 private SMALLER_SUM; // 291573500000000000000 uint256 private MEDIUM_SUM; // 485955800000000000000 uint256 private BIGGER_SUM; // 971911700000000000000 uint256 private BIGGEST_SUM; // 1943823500000000000000 // Vesting period uint256 public duration = 23667695; // Flag of Finalized sale event bool public isFinalized = false; // Wei raides accumulator uint256 public weiRaised = 0; // Token public token; // address public wallet; uint256 public rate; uint256 public softCap; uint256 public hardCap; /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold * @param _softCap Soft cap * @param _hardCap Hard cap * @param _smallestSum Sum after which investor receives 5% of bonus tokens to vesting contract * @param _smallerSum Sum after which investor receives 10% of bonus tokens to vesting contract * @param _mediumSum Sum after which investor receives 15% of bonus tokens to vesting contract * @param _biggerSum Sum after which investor receives 20% of bonus tokens to vesting contract * @param _biggestSum Sum after which investor receives 30% of bonus tokens to vesting contract */ constructor( uint256 _rate, address _wallet, Token _token, uint256 _softCap, uint256 _hardCap, uint256 _smallestSum, uint256 _smallerSum, uint256 _mediumSum, uint256 _biggerSum, uint256 _biggestSum ) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); require(_hardCap > 0); require(_softCap > 0); require(_hardCap > _softCap); rate = _rate; wallet = _wallet; token = _token; hardCap = _hardCap; softCap = _softCap; SMALLEST_SUM = _smallestSum; SMALLER_SUM = _smallerSum; MEDIUM_SUM = _mediumSum; BIGGER_SUM = _biggerSum; BIGGEST_SUM = _biggestSum; owners[msg.sender] = true; /** * Pie chart * * early cotributors => 1 * management team => 2 * advisors => 3 * partners => 4 * community => 5 * company => 6 * liquidity => 7 * sale => 8 */ pieChart[1] = PartInfo(10, true, token.totalSupply().mul(10).div(100)); pieChart[2] = PartInfo(15, true, token.totalSupply().mul(15).div(100)); pieChart[3] = PartInfo(5, true, token.totalSupply().mul(5).div(100)); pieChart[4] = PartInfo(5, false, token.totalSupply().mul(5).div(100)); pieChart[5] = PartInfo(8, false, token.totalSupply().mul(8).div(100)); pieChart[6] = PartInfo(17, false, token.totalSupply().mul(17).div(100)); pieChart[7] = PartInfo(10, false, token.totalSupply().mul(10).div(100)); pieChart[8] = PartInfo(30, false, token.totalSupply().mul(30).div(100)); } // ----------------------------------------- // Allocation external interface // ----------------------------------------- /** * Function for buying tokens */ function() external payable { buyTokens(msg.sender); } /** * Check if value respects sale minimal contribution sum */ modifier respectContribution() { require( msg.value >= SMALLEST_SUM, "Minimum contribution is $50,000" ); _; } /** * Check if sale is still open */ modifier onlyWhileOpen { require(!isFinalized, "Sale is closed"); _; } /** * Check if sender is owner */ modifier onlyOwner { require(isOwner(msg.sender) == true, "User is not in Owners"); _; } /** * Add new owner * @param _owner Address of owner which should be added */ function addOwner(address _owner) public onlyOwner { require(owners[_owner] == false); owners[_owner] = true; } /** * Delete an onwer * @param _owner Address of owner which should be deleted */ function deleteOwner(address _owner) public onlyOwner { require(owners[_owner] == true); owners[_owner] = false; } /** * Check if sender is owner * @param _address Address of owner which should be checked */ function isOwner(address _address) public view returns(bool res) { return owners[_address]; } /** * Allocate tokens to provided investors */ function allocateTokens(address[] _investors) public onlyOwner { require(_investors.length <= 50); for (uint i = 0; i < _investors.length; i++) { allocateTokensInternal(_investors[i]); } } /** * Allocate tokens to a single investor * @param _contributor Address of the investor */ function allocateTokensForContributor(address _contributor) public onlyOwner { allocateTokensInternal(_contributor); } /* * Allocates tokens to single investor * @param _contributor Investor address */ function allocateTokensInternal(address _contributor) internal { uint256 weiAmount = contributors[_contributor]; if (weiAmount > 0) { uint256 tokens = _getTokenAmount(weiAmount); uint256 bonusTokens = _getBonusTokens(weiAmount); pieChart[8].amount = pieChart[8].amount.sub(tokens); pieChart[1].amount = pieChart[1].amount.sub(bonusTokens); contributors[_contributor] = 0; token.transfer(_contributor, tokens); createTimeBasedVesting(_contributor, bonusTokens); } } /** * Send funds from any part of pieChart * @param _to Investors address * @param _type Part of pieChart * @param _amount Amount of tokens */ function sendFunds(address _to, uint256 _type, uint256 _amount) public onlyOwner { require( pieChart[_type].amount >= _amount && _type >= 1 && _type <= 8 ); if (pieChart[_type].lockup == true) { createTimeBasedVesting(_to, _amount); } else { token.transfer(_to, _amount); } pieChart[_type].amount -= _amount; } /** * Investment receiver * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created without bonuses uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); // update contributors[_beneficiary] += weiAmount; if(!isInvestor[_beneficiary]){ investors.push(_beneficiary); isInvestor[_beneficiary] = true; } _forwardFunds(); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase ( address _beneficiary, uint256 _weiAmount ) onlyIfWhitelisted(_beneficiary) respectContribution onlyWhileOpen view internal { require(weiRaised.add(_weiAmount) <= hardCap); require(_beneficiary != address(0)); } /** * Create vesting contract * @param _beneficiary address of person who will get all tokens as vesting ends * @param _tokens amount of vested tokens */ function createTimeBasedVesting ( address _beneficiary, uint256 _tokens ) internal { uint256 _start = block.timestamp; TokenVesting tokenVesting; if (vesting[_beneficiary] == address(0)) { tokenVesting = new TokenVesting(_beneficiary, _start, false); vesting[_beneficiary] = tokenVesting; } else { tokenVesting = vesting[_beneficiary]; } token.transfer(address(tokenVesting), _tokens); emit TimeVestingCreation(_beneficiary, _start, duration, false); } /** * checks if sale is closed */ function hasClosed() public view returns (bool) { return isFinalized; } /** * Release tokens from vesting contract */ function releaseVestedTokens() public { address beneficiary = msg.sender; require(vesting[beneficiary] != address(0)); TokenVesting tokenVesting = vesting[beneficiary]; tokenVesting.release(token); } /** * 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 _getBonusTokens ( uint256 _weiAmount ) internal view returns (uint256 purchasedAmount) { purchasedAmount = _weiAmount; if (_weiAmount >= SMALLEST_SUM && _weiAmount < SMALLER_SUM) { purchasedAmount = _weiAmount.perc(5); } if (_weiAmount >= SMALLER_SUM && _weiAmount < MEDIUM_SUM) { purchasedAmount = _weiAmount.perc(10); } if (_weiAmount >= MEDIUM_SUM && _weiAmount < BIGGER_SUM) { purchasedAmount = _weiAmount.perc(15); } if (_weiAmount >= BIGGER_SUM && _weiAmount < BIGGEST_SUM) { purchasedAmount = _weiAmount.perc(20); } if (_weiAmount >= BIGGEST_SUM) { purchasedAmount = _weiAmount.perc(30); } return purchasedAmount.mul(rate); } function _getTokenAmount ( uint256 _weiAmount ) internal view returns (uint256 purchasedAmount) { return _weiAmount.mul(rate); } /** * Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } /** * Must be called after sale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!hasClosed()); finalization(); isFinalized = true; emit Finalized(); } /** * Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() pure internal {} }
Investment receiver _beneficiary Address performing the token purchase/ calculate token amount to be created without bonuses update state update
function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); contributors[_beneficiary] += weiAmount; if(!isInvestor[_beneficiary]){ investors.push(_beneficiary); isInvestor[_beneficiary] = true; } _forwardFunds(); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); }
5,424,190
./partial_match/1/0x6429b42da2a06aA1C46710509fC96E846F46181e/sources/contracts/Holograph.sol
Get the chain ID that the Protocol was deployed on Useful for checking if/when a hard fork occurs/
function getChainId() external view returns (uint256 chainId) { assembly { chainId := sload(_chainIdSlot) } }
4,333,321
pragma solidity ^0.4.13; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { 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) constant 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract 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 recieve 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 returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract ChangeCoin is MintableToken { string public name = "Change COIN"; string public symbol = "CAG"; uint256 public decimals = 18; bool public tradingStarted = false; /** * @dev modifier that throws if trading has not started yet */ modifier hasStartedTrading() { require(tradingStarted); _; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function startTrading() onlyOwner { tradingStarted = true; } /** * @dev Allows anyone to transfer the Simis tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) hasStartedTrading returns (bool){ super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the PAY tokens once trading has started * @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 uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) hasStartedTrading returns (bool){ super.transferFrom(_from, _to, _value); } } contract ChangeCoinCrowdsale is Ownable { using SafeMath for uint256; // The token being sold ChangeCoin public token; // start and end block where investments are allowed (both inclusive) uint256 public startBlock; uint256 public endBlock; // address where funds are collected address public multiSigWallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; uint256 public minContribution; uint256 public hardcap; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event MainSaleClosed(); uint256 public raisedInPresale = 0.5 ether; function ChangeCoinCrowdsale() { startBlock = 4204545; endBlock = 4215000; rate = 500; multiSigWallet = 0xCe5574fF9d1fD16A411c09c488935F4fc613498c; token = ChangeCoin(0x9C3386DeBA43A24B3653F35926D9DA8CBABC3FEC); minContribution = 0 ether; hardcap = 2 ether; //minContribution = 0.5 ether; //hardcap = 250000 ether; require(startBlock >= block.number); require(endBlock >= startBlock); } /** * @dev Calculates the amount of bonus coins the buyer gets * @param tokens uint the amount of tokens you get according to current rate * @return uint the amount of bonus tokens the buyer gets */ function bonusAmmount(uint256 tokens) internal returns(uint256) { uint256 bonus5 = tokens.div(20); // add bonus 20% in first 48hours, 15% in next 24h, 5% in next 24h if (block.number < startBlock.add(10160)) { // 5080 is aprox 24h return tokens.add(bonus5.mul(4)); } else if (block.number < startBlock.add(15240)) { return tokens.add(bonus5.mul(3)); } else if (block.number < startBlock.add(20320)) { return tokens.add(bonus5); } else { return 0; } } // @return true if valid purchase function validPurchase() internal constant returns (bool) { uint256 current = block.number; bool withinPeriod = current >= startBlock && current <= endBlock; bool nonZeroPurchase = msg.value >= minContribution; bool withinCap = weiRaised.add(msg.value).add(raisedInPresale) <= hardcap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool timeLimitReached = block.number > endBlock; bool capReached = weiRaised.add(raisedInPresale) >= hardcap; return timeLimitReached || capReached; } // low level token purchase function function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); tokens = tokens + bonusAmmount(tokens); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); multiSigWallet.transfer(msg.value); } // finish mining coins and transfer ownership of Change coin to owner function finishMinting() public onlyOwner { uint issuedTokenSupply = token.totalSupply(); uint restrictedTokens = issuedTokenSupply.mul(60).div(40); token.mint(multiSigWallet, restrictedTokens); token.finishMinting(); token.transferOwnership(owner); MainSaleClosed(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } }
finish mining coins and transfer ownership of Change coin to owner
function finishMinting() public onlyOwner { uint issuedTokenSupply = token.totalSupply(); uint restrictedTokens = issuedTokenSupply.mul(60).div(40); token.mint(multiSigWallet, restrictedTokens); token.finishMinting(); token.transferOwnership(owner); MainSaleClosed(); }
7,235,093
./full_match/4/0x164c24d0844c267DA15a4c841eaBae817d211EA1/sources/Users/hristiyangeorgiev/Documents/Projects/Redemeum/ERC20/bsn-core-prototype/contracts/VoucherKernel.sol
Get the address of the token where the price for the supply is held _tokenIdSupply ID of the voucher token return Address of the token/
function getVoucherPriceToken(uint256 _tokenIdSupply) public view returns (address) { return paymentDetails[_tokenIdSupply].addressTokenPrice; }
13,350,966
./full_match/1/0x6CB6107f84c7559707AF026C9ED83cfc5DCb72E9/sources/contracts/USDM.sol
Private function that blocklists the specified address. account The address to blocklist. Note: This function does not perform any checks against the zero address for gas efficiency. It is the caller's responsibility to ensure that the zero address is not provided as `account`. Blocking the zero address could have unintended effects on token minting and burning./
function _blockAccount(address account) private { if (isBlocked(account)) { revert USDMInvalidBlockedAccount(account); } _blocklist[account] = true; emit AccountBlocked(account); }
9,652,346
./full_match/42/0xceaeaB2C35514156b4cd1ee1Ce9ef976Fd9A0BF6/sources/contracts/UdemyAuction2.sol
the main function called to place a bid to place a bid auction should be running minimum value allowed to be sent require(msg.value > 0.0001 ether); the currentBid should be greater than the highestBindingBid. Otherwise there's nothing to do.odšteje prejšnjo od skupne updating the mapping variablecurrentBid and bids[msg.sender] sta skupek vsot------------------------------------------------------------------------------------frontend use - real time pricesso on the first bid we add starting price to the incrementwinningBid[highestBindingBid] = msg.sender;
function placeBid() public payable notOwner afterStart beforeEnd returns(bool){ require(auctionState == State.Running); require(msg.value >= items[owner].startingPrice, "Value must be higher than the starting bid price!"); require(currentBid > highestBindingBid, "the currentBid must me greater than the HBB!"); firstBid += 1; bids[msg.sender] = currentBid; if(firstBid == 1){ highestBindingBidRT = min(deductBids + items[owner].itemIncrement, bidTest[highestBidderRT]); highestBidderRT = payable(msg.sender); } }
9,596,705
pragma solidity >=0.8.0 <0.9.0; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./FriendrCoin.sol"; contract FriendrChain is OwnableUpgradeable { event messageSent(address sender, address receiver, uint256 messageIdx); event publicMessageSent(address sender, uint256 publicMessageIdx); event messageVoted(uint256 publicMessageIdx, bool isUpvote); event swipeMatch(address swiper, address swipee); struct Profile { string name; address _address; string image; string bio; string socialMediaProfile; uint256 created_ts; uint256 deleted_ts; } struct Message { string text; address sender; bool isPublic; uint256 created_ts; uint256 deleted_ts; // TODO: is this used? I think we need to store message idx in this struct if we want to be able to delete, so that FE has index number to send to delete API } struct PublicMessage { Message message; uint256 upvotes; uint256 downvotes; address author; string authorImg; uint256 idx; } modifier onlySenderOrOwner(address _profile) { require( _profile == _msgSender() || owner() == _msgSender(), "Caller is neither the target address nor owner nor proxy admin." ); _; } mapping(address => Profile) private _profiles; // profile for an address mapping(address => mapping(address => bool)) private _swipedAddresses; // addresses swiped on by address (value indexed by address for lookup) mapping(address => mapping(address => bool)) private _swipedRightAddresses; // addresses swiped right on by address (value indexed by address for lookup) mapping(address => mapping(uint256 => address)) private _matches; // addresses matched by address mapping(address => uint256) private _matches_count; // number of matches by address used for indexed match lookup mapping(bytes => mapping(uint256 => Message)) private _messages; // message history by address pair packed into bytes using map for lookups mapping(bytes => uint256) private _messages_count; // count of messages by message pair used for lookups in _messages mapping(uint256 => address) private _accounts; // indexed list of all accounts in the contract mapping(uint256 => PublicMessage) private _public_messages; // indexed list of public messages mapping(address => mapping(uint256 => bool)) _votes_cast_by_user; // tracking which public messages a user has already voted on FriendrCoin private friendrCoin; // note that coins are issued in wei, so we need to multiply all by (10 ** 18) uint256 private initTokenReward; uint256 private defaultApprovalAmt; string public defaultMessageText; uint256 public profileCount; uint256 public publicMessageCount; uint256 private constant oneHundredMillion = 1000 * 1000 * 1000 * (10**18); // need to multiply it into wei uint256 private constant twentyMillion = oneHundredMillion / 5; uint256 private constant eightyMillion = twentyMillion * 4; function initialize() external initializer { __Ownable_init(); // mint 20% to deployer and the rest to the contract friendrCoin = new FriendrCoin( "FriendrCOIN", "FRIEND", twentyMillion, eightyMillion, owner(), address(this) ); profileCount = 0; // Init to 0 publicMessageCount = 0; // Init to 0 initTokenReward = 100 * (10**18); defaultApprovalAmt = 10000000 * (10**18); defaultMessageText = "This is the beginning of your message history."; } /** * Public Read APIs */ // Used by FE login flow to determine if wallet user has already created a profile // If Profile object created_ts == 0, then it is a default profile (not yet created) function getUserProfile(address _profile) public view returns (Profile memory) { Profile storage profile = _profiles[_profile]; if (profile.deleted_ts != 0) { // return the 0 address which we define to be nil return _profiles[address(0)]; } return profile; } function getUnseenProfiles( address _profile, uint256 limit, uint256 offset, bool isBurner ) public view returns ( Profile[] memory, uint256, uint256 ) { require( offset < profileCount, "Cannot fetch profiles indexed beyond those that exist in system" ); uint256 profileRtnCount = 0; uint256 ownTokenBalanceTier = getTokenTier( getTokenBalanceOfUser(_profile) ); Profile[] memory profiles = new Profile[](limit); uint256 missedProfiles = 0; while (profileRtnCount < limit && offset < profileCount) { // get account at index offset address currAcct = _accounts[offset]; // skip if _profile is the same as currAct if (_profile != currAcct) { // see if currAcct was already swiped by _profile // but if caller is burner wallet then we don't need to do profile lookup bool alreadySwiped = isBurner ? false : _swipedAddresses[_profile][currAcct]; if (!alreadySwiped) { uint256 counterpartyTokenBalance = getTokenBalanceOfUser( currAcct ); if ( getTokenTier(counterpartyTokenBalance) <= ownTokenBalanceTier ) { // get profile for currAcct Profile memory profToShowInQueue = _profiles[currAcct]; // if profToShowInQueue is not deleted, then add it to rtnList if (profToShowInQueue.deleted_ts == 0) { profiles[profileRtnCount] = profToShowInQueue; profileRtnCount++; } } else { missedProfiles++; } } } offset++; } // we want to return an array of the exact correct size Profile[] memory profilesToRtn = new Profile[](profileRtnCount); for (uint256 i = 0; i < profileRtnCount; i++) { profilesToRtn[i] = profiles[i]; } return (profilesToRtn, offset, missedProfiles); } function getIsMatch(address swiper, address swipee) public view returns (bool) { return _swipedRightAddresses[swiper][swipee] && _swipedRightAddresses[swipee][swiper]; } // This endpoint serves the messages loading page to see all people with whom there were recent messages // It returns profiles to display on the page that a user can click into to see message history // As well as a new offset for pagination purposes // TODO: modify this to return most recent page of conversations function getRecentMatches( address _profile, uint256 limit, uint256 offset ) public view returns (Profile[] memory, uint256) { // Fetch a page of matches uint256 matchesCount = _matches_count[_profile]; require( offset < matchesCount, "Cannot read matches indexed beyond total number of matches for this user" ); uint256 profileRtnCount = 0; Profile[] memory profiles = new Profile[](limit); while (profileRtnCount < limit && offset < matchesCount) { address _match = _matches[_profile][offset]; Profile memory _match_profile = _profiles[_match]; if (_match_profile.deleted_ts == 0) { profiles[profileRtnCount] = _match_profile; profileRtnCount++; } offset++; } // we want to return an array of the exact correct size Profile[] memory profilesToRtn = new Profile[](profileRtnCount); for (uint256 i = 0; i < profileRtnCount; i++) { profilesToRtn[i] = profiles[i]; } return (profilesToRtn, offset); } // Called when user clicks into a conversation with a match function getRecentMessagesForMatch( address _address1, address _address2, uint256 limit, uint256 offset ) public view returns (Message[] memory, uint256) { require( _address1 != _address2, "Cannot send/receive messages to/from self." ); // Note that matchKeyPair can be address1:address2 or address2:address1 depending on order of creation // So need to try other order pair if first try returns 0 matches (all matches have at least 1 match bc of default match) bytes memory matchKeyPair = fetchMessageKeyPair(_address1, _address2); uint256 messageCount = _messages_count[matchKeyPair]; require( offset < messageCount, "Cannot read messages indexed beyond total number of messages for this pair" ); Message[] memory messages = new Message[](limit); uint256 messagesToRtnCount = 0; while (messagesToRtnCount < limit && offset < messageCount) { Message memory message = _messages[matchKeyPair][offset]; if (message.deleted_ts == 0) { messages[messagesToRtnCount] = message; messagesToRtnCount++; } offset++; } // we want to return an array of the exact correct size Message[] memory messagesToRtn = new Message[](messagesToRtnCount); for (uint256 i = 0; i < messagesToRtnCount; i++) { messagesToRtn[i] = messages[i]; } return (messagesToRtn, offset); } // Called on public message dashboard load // TODO: figure out how to sort these by vote function getPublicMessages(uint256 limit, uint256 offset) public view returns (PublicMessage[] memory, uint256) { require( offset < publicMessageCount, "Cannot read public messages indexed beyond total number of public messages that exist" ); PublicMessage[] memory messages = new PublicMessage[](limit); uint256 messagesToRtnCount = 0; while (messagesToRtnCount < limit && offset < publicMessageCount) { PublicMessage memory message = _public_messages[offset]; messages[messagesToRtnCount] = message; messagesToRtnCount++; offset++; } // we want to return an array of the exact correct size PublicMessage[] memory messagesToRtn = new PublicMessage[]( messagesToRtnCount ); for (uint256 i = 0; i < messagesToRtnCount; i++) { messagesToRtn[i] = messages[i]; } return (messagesToRtn, offset); } // Gets balance of token for given wallet function getTokenBalanceOfUser(address _profile) public view returns (uint256) { return friendrCoin.balanceOf(_profile); } // Gets wallet address of FriendrCoin function getTokenAddress() public view returns (address) { return address(friendrCoin); } /** * Public Write APIs */ function createUserProfileFlow( address _profile, string memory name, string memory _image, string memory bio, string memory _socialMediaProfile ) public { require( _profile != address(0), "Cannot create a profile at the 0 address" ); // This function adds tokens to the profile upon creation // So require that a profile cannot already exist for the given address // Use updateUserProfile method to update existing profile (it does not pay tokens) Profile storage profile = _profiles[_profile]; if (profile.deleted_ts != 0) { // calling create for a deleted profile means to re-activate it profile.deleted_ts = 0; } else { // if the profile is not deleted, then we ensure it doesn't already exist require( profile.created_ts == 0, "Cannot create a profile that already exists." ); } profile.name = name; profile._address = _profile; profile.image = _image; profile.bio = bio; profile.socialMediaProfile = _socialMediaProfile; profile.created_ts = block.timestamp; // Add profile to indexed list of accounts and increment counter _accounts[profileCount] = _profile; profileCount++; // Approve this contract to spend tokens for _profile's wallet friendrCoin.approveFor(_profile, defaultApprovalAmt); // Now send tokens from this contract's wallet to _profile's wallet // Be sure that we only transfer after setting profile.created_ts because otherwise vulnerable to reentrancy attack friendrCoin.transferFrom(address(this), _profile, initTokenReward); } function swipeLeft(address _userProfile, address _swipedProfile) public { _swipedAddresses[_userProfile][_swipedProfile] = true; } function swipeRight(address _userProfile, address _swipedProfile) public { require( friendrCoin.balanceOf(_userProfile) > 0, "User doesn't have enough tokens to swipe right" ); _swipedAddresses[_userProfile][_swipedProfile] = true; _swipedRightAddresses[_userProfile][_swipedProfile] = true; // Performance optimization is to first check if match before transferring // That way don't need to transfer and then transfer back in case of match bool isMatch = _swipedRightAddresses[_swipedProfile][_userProfile]; if (isMatch) { // get number of matches for both swiper and swipee uint256 userMatchCount = _matches_count[_userProfile]; uint256 swipedMatchCount = _matches_count[_swipedProfile]; // set swiped profile as Nth match for both swiper and swipee _matches[_userProfile][userMatchCount] = _swipedProfile; _matches[_swipedProfile][swipedMatchCount] = _userProfile; // increment match count for swiper and swipee _matches_count[_userProfile]++; _matches_count[_swipedProfile]++; // Now need to return 1 token back to _swipedProfile since they didn't match initially and were thus charged one token friendrCoin.transferFrom( address(this), _swipedProfile, 1 * (10**18) ); // Now need to init default message in messages mapping bytes memory messageMapKey = buildAddressKeyPair( _userProfile, _swipedProfile ); uint256 message_ts = block.timestamp; Message memory message = Message({ text: defaultMessageText, sender: address(this), // use contract address as sender of initial message isPublic: false, created_ts: message_ts, deleted_ts: 0 }); // set the default message to index 0 and then increment message index uint256 messages_idx = _messages_count[messageMapKey]; _messages[messageMapKey][messages_idx] = message; _messages_count[messageMapKey]++; emit swipeMatch(_userProfile, _swipedProfile); } else { friendrCoin.transferFrom(_userProfile, address(this), 1 * (10**18)); } } function sendMessage( address _sender, address _receiver, string memory _text, bool _isPublic ) public { bytes memory matchKeyPair = fetchMessageKeyPair(_sender, _receiver); uint256 messageCount = _messages_count[matchKeyPair]; // now add message to end of message history for the pair and increment counter Message memory message = Message({ text: _text, sender: _sender, isPublic: _isPublic, created_ts: block.timestamp, deleted_ts: 0 }); _messages[matchKeyPair][messageCount] = message; // emit event before incrementing messageCount index so that event points to the most recent message emit messageSent(_sender, _receiver, messageCount); _messages_count[matchKeyPair]++; // if message is public, add it to indexed mapping of public messages if (_isPublic) { PublicMessage memory publicMessage = PublicMessage({ message: message, upvotes: 0, downvotes: 0, author: _sender, authorImg: _profiles[_sender].image, idx: publicMessageCount }); _public_messages[publicMessageCount] = publicMessage; // emit event before incrementing publicMessageCount index so that event points to the most recent message emit publicMessageSent(_sender, publicMessageCount); publicMessageCount++; } } function voteOnPublicMessage(uint256 publicMessageIdx, bool isUpvote) public { require( publicMessageIdx < publicMessageCount, "Cannot vote on a message that is beyond bounds of public message list" ); PublicMessage storage message = _public_messages[publicMessageIdx]; require( _msgSender() != message.author || _msgSender() == owner(), "Cannot vote on your own message" ); require( !didAlreadyVoteOnMessage(_msgSender(), publicMessageIdx) || _msgSender() == owner(), "Can only vote on a message once." ); // Now they're voting on this message _votes_cast_by_user[_msgSender()][publicMessageIdx] = true; if (isUpvote) { message.upvotes++; friendrCoin.transferFrom( address(this), message.author, 1 * (10**18) ); } else { if (message.upvotes - message.downvotes > 0) { // Can only transfer tokens away from author of publicMessage if vote count is positive friendrCoin.transferFrom( message.author, address(this), 1 * (10**18) ); } message.downvotes++; } emit messageVoted(publicMessageIdx, isUpvote); } function editProfile( address _profile, bool editName, string memory newName, bool editImage, string memory newImage, bool editBio, string memory newBio, bool editSocialMediaProfileLink, string memory newSocialMediaProfileLink ) public { require( _profiles[_profile].created_ts > 0, "Profile is not yet created" ); if (editSocialMediaProfileLink) { _profiles[_profile].socialMediaProfile = newSocialMediaProfileLink; } if (editName) { _profiles[_profile].name = newName; } if (editImage) { _profiles[_profile].image = newImage; } if (editBio) { _profiles[_profile].bio = newBio; } } function deleteProfileImage(address _profile) public { require( _profiles[_profile].created_ts > 0, "Profile is not yet created" ); _profiles[_profile].image = ""; } function deleteProfile(address _profile) public { require( _profiles[_profile].created_ts > 0, "Profile is not yet created" ); _profiles[_profile].deleted_ts = block.timestamp; } /** * Helper methods */ function buildAddressKeyPair(address _userProfile, address _swipedProfile) private pure returns (bytes memory) { return abi.encodePacked(_userProfile, _swipedProfile); } // Helper method to determine correct ordering of address1:address2 vs address2:address1 for storing messages function fetchMessageKeyPair(address _address1, address _address2) private view returns (bytes memory) { bytes memory matchKeyPair = buildAddressKeyPair(_address1, _address2); uint256 messageCount = _messages_count[matchKeyPair]; if (messageCount == 0) { // Try other pair ordering matchKeyPair = buildAddressKeyPair(_address2, _address1); messageCount = _messages_count[matchKeyPair]; // If message count is still 0, then we have an issue require( messageCount > 0, "Profile pair doesn't have any messages, perhaps match was never initialized" ); } return matchKeyPair; } function didAlreadyVoteOnMessage(address voter, uint256 publicMessageIdx) private view returns (bool) { return _votes_cast_by_user[voter][publicMessageIdx]; } function getTokenTier(uint256 tokenCount) private pure returns (uint256) { uint256 myTier = 0; while (tokenCount != 0) { tokenCount /= 10; myTier++; } return myTier; } /** * Owner-only getters and setters */ function setInitTokenReward(uint256 _newReward) public onlyOwner { initTokenReward = _newReward; } function getInitTokenReward() public view onlyOwner returns (uint256) { return initTokenReward; } function setDefaultApprovalAmt(uint256 _newDefaultApprovalAmt) public onlyOwner { defaultApprovalAmt = _newDefaultApprovalAmt; } function getDefaultApprovalAmt() public view onlyOwner returns (uint256) { return defaultApprovalAmt; } function setDefaultMessageText(string memory _text) public onlyOwner { defaultMessageText = _text; } }
mint 20% to deployer and the rest to the contract
function initialize() external initializer { __Ownable_init(); friendrCoin = new FriendrCoin( "FriendrCOIN", "FRIEND", twentyMillion, eightyMillion, owner(), address(this) ); initTokenReward = 100 * (10**18); defaultApprovalAmt = 10000000 * (10**18); defaultMessageText = "This is the beginning of your message history."; }
1,035,567
/* Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions. */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./ProxyRegistry.sol"; import "./TokenRecipient.sol"; import "./proxy/OwnedUpgradeabilityStorage.sol"; /** * @title AuthenticatedProxy * @author Wyvern Protocol Developers */ contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize(address addrUser, ProxyRegistry addrRegistry) public { require(!initialized, "Authenticated proxy already initialized"); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require( msg.sender == user, "Authenticated proxy can only be revoked by its user" ); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as * long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param data Calldata to send * @return result Result of the call (success or failure) */ function proxy( address dest, HowToCall howToCall, bytes memory data ) external returns (bool result, string memory reason) { return _proxy(dest, howToCall, data); } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param data Calldata to send */ function proxyAssert( address dest, HowToCall howToCall, bytes memory data ) external { (bool result, string memory revertReason) = _proxy( dest, howToCall, data ); require( result, string(abi.encodePacked("Call failed - ", revertReason)) ); } function _proxy( address dest, HowToCall howToCall, bytes memory data ) internal returns (bool result, string memory reason) { require( msg.sender == user || (!revoked && registry.contracts(msg.sender)), "Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access" ); result = false; bytes memory ret; if (howToCall == HowToCall.Call) { (result, ret) = dest.call(data); } else if (howToCall == HowToCall.DelegateCall) { (result, ret) = dest.delegatecall(data); } if (!result) reason = _getRevertMsg(ret); return (result, reason); } function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } }
Execute a message call from the proxy contract Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access dest Address to which the call will be sent howToCall Which kind of call to make data Calldata to send return result Result of the call (success or failure)/
function proxy( address dest, HowToCall howToCall, bytes memory data ) external returns (bool result, string memory reason) { return _proxy(dest, howToCall, data); }
12,691,434
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 less than or equal to `b`. a a FixedPoint.Signed. 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; }
98,897
pragma solidity >=0.4.22 <0.7.0; /** * @title Standard ERC20 token Exchanger * @author github.com/Akif-G * @notice Basic ERC20 token Exchange mechanism implementation, Not recommended for commercial usage. * @dev Implementation of the basic standard token, can be used for referance without guarranty. * https://github.com/Akif-G/ERC20-Basic-Token */ import "erc20_TemplateToken.sol"; contract Exchanger{ address nftAddress = address(this); address payable _wallet = address(uint160(nftAddress)); address payable House; /// @notice House is set via deploying contract constructor()public{ House = msg.sender; } /// @notice returns the contract cretor's address if needed function getExchangerAddress()public view returns(address){ return House; } /// @notice returns contract address, to be used for validating the exchange contract function getContactAddress()public view returns(address){ return _wallet; } /// @notice transfers two tokens from contract addresses, an amount and permissions. /// @dev requires validated permissions and enough token, from both House and User. House gets the spent token and gives the requested one. /// @param from_addrs address of the token that will be spent /// @param to_addrs address of the token that will be converted to /// @param amount amount of the tokens that will be converted function transfer(address from_addrs, address to_addrs, uint256 amount) public returns(bool success){ MehmetGultekinToken first = MehmetGultekinToken(from_addrs); MehmetGultekinToken second = MehmetGultekinToken(to_addrs); assert(amount>0); require(first.balanceOf(msg.sender)>=amount, "not enough token to Exchange"); require(second.balanceOf(House)>=amount, "not enough token in Exchange Contract's Creator"); require(first.allowance(msg.sender,_wallet)>=amount, "transfer amount exceeds allowance"); require(second.allowance(House,_wallet)>=amount, "transfer amount exceeds allowance for Exchange Contract"); first.transferFrom(msg.sender,House,amount); second.transferFrom(House,msg.sender,amount); return true; } }
transfers two tokens from contract addresses, an amount and permissions. requires validated permissions and enough token, from both House and User. House gets the spent token and gives the requested one. from_addrs address of the token that will be spent to_addrs address of the token that will be converted to amount amount of the tokens that will be converted
function transfer(address from_addrs, address to_addrs, uint256 amount) public returns(bool success){ MehmetGultekinToken first = MehmetGultekinToken(from_addrs); MehmetGultekinToken second = MehmetGultekinToken(to_addrs); assert(amount>0); require(first.balanceOf(msg.sender)>=amount, "not enough token to Exchange"); require(second.balanceOf(House)>=amount, "not enough token in Exchange Contract's Creator"); require(first.allowance(msg.sender,_wallet)>=amount, "transfer amount exceeds allowance"); require(second.allowance(House,_wallet)>=amount, "transfer amount exceeds allowance for Exchange Contract"); first.transferFrom(msg.sender,House,amount); second.transferFrom(House,msg.sender,amount); return true; }
7,221,849
pragma solidity 0.5.12; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IComptroller.sol"; import "./interfaces/ICToken.sol"; import "./interfaces/ICEther.sol"; contract LiquidatorManager is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; address public comptrollerAddress = address( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address private constant ETHAddress = address( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); mapping(address => mapping(address => uint256)) public balance; event AmountDeposited(address token, uint256 amount); event AmountWithdrawn(address token, uint256 amount); event AccountLiquidated( address borrower, address liquidator, address assetSeized, uint256 amountSeized ); event AmountRepaid(address borrower, address payer, uint256 amount); function updateComptrollerAddress(address _comptrollerAddress) public onlyOwner { require( _comptrollerAddress != address(0), "Invalid comptroller address" ); comptrollerAddress = _comptrollerAddress; } function deposit(address token, uint256 amount) public payable { require(token != address(0), "Invalid Token address"); require(amount > 0, "Invalid token amount"); if (token == ETHAddress) { require(msg.value == amount, "Incorrect ETH amount"); return _depositETH(msg.value); } uint256 allowance = IERC20(token).allowance(msg.sender, address(this)); require(allowance >= amount, "Tokens not approved"); balance[msg.sender][token] = (balance[msg.sender][token]).add(amount); IERC20(token).transferFrom(msg.sender, address(this), amount); emit AmountDeposited(token, amount); } function _depositETH(uint256 amount) internal { balance[msg.sender][ETHAddress] = balance[msg.sender][ETHAddress].add( amount ); emit AmountDeposited(ETHAddress, amount); } function withdraw(address token, uint256 amount) public { require(token != address(0), "Invalid Token address"); require(amount > 0, "Invalid token amount"); require( balance[msg.sender][token] >= amount, "Invalid withdrawal amount" ); balance[msg.sender][token] = balance[msg.sender][token].sub(amount); if (token == ETHAddress) { msg.sender.transfer(amount); } else { IERC20(token).transfer(msg.sender, amount); } emit AmountWithdrawn(token, amount); } function withdrawCTokens( address token, address cToken, uint256 amount ) public returns (uint256 tokensMinted) { require(token != address(0), "Invalid Token address"); require(amount > 0, "Invalid token amount"); require( balance[msg.sender][token] >= amount, "Invalid withdrawal amount" ); balance[msg.sender][token] = balance[msg.sender][token].sub(amount); uint256 initialCTokenBalance = IERC20(cToken).balanceOf(address(this)); //mint cToken if (token == ETHAddress) { ICEther(cToken).mint.value(amount)(); } else { //approve IERC20(token).approve(cToken, amount); require( ICToken(cToken).mint(amount) == 0, "Error in redeeming tokens" ); } tokensMinted = IERC20(cToken).balanceOf(address(this)).sub( initialCTokenBalance ); IERC20(cToken).transfer(msg.sender, tokensMinted); emit AmountWithdrawn(cToken, amount); } function isLiquidityNegative() public view returns (bool) { (, , uint256 shortfall) = IComptroller(comptrollerAddress) .getAccountLiquidity(msg.sender); if (shortfall > 0) return true; return false; } //amount in underlying asset terms function repayBorrowedAsset( address borrower, address cToken, uint256 repayAmount ) public { address underlyingToken = ICToken(cToken).underlying(); require( balance[msg.sender][underlyingToken] >= repayAmount, "Insufficient deposit" ); balance[msg.sender][underlyingToken] = balance[msg .sender][underlyingToken] .sub(repayAmount); //repay if (borrower == msg.sender) { _repayBorrow(underlyingToken, cToken, repayAmount); } else { _repayBorrowBehalf(underlyingToken, borrower, cToken, repayAmount); } emit AmountRepaid(borrower, msg.sender, repayAmount); } function _repayBorrow( address underlyingToken, address cToken, uint256 repayAmount ) internal { if (underlyingToken == ETHAddress) { ICEther(cToken).repayBorrow.value(repayAmount)(); } else { //approve IERC20(underlyingToken).approve(cToken, repayAmount); require( ICToken(cToken).repayBorrow(repayAmount) == 0, "Error in repay" ); } } function _repayBorrowBehalf( address underlyingToken, address borrower, address cToken, uint256 repayAmount ) internal { if (underlyingToken == ETHAddress) { ICEther(cToken).repayBorrowBehalf.value(repayAmount)(borrower); } else { //approve IERC20(underlyingToken).approve(cToken, repayAmount); require( ICToken(cToken).repayBorrowBehalf(borrower, repayAmount) == 0, "Error in repay" ); } } function liquidate( address borrower, address collateral, address borrowedAsset, uint256 amount ) public returns (uint256 collateralSeized) { address underlyingAsset = ICToken(borrowedAsset).underlying(); require( balance[msg.sender][underlyingAsset] >= amount, "Insufficient deposit" ); uint256 collateralInitialbalance = IERC20(collateral).balanceOf( address(this) ); balance[msg.sender][underlyingAsset] = balance[msg .sender][underlyingAsset] .sub(amount); //liquidate if (underlyingAsset == ETHAddress) { _liquidateETH(borrowedAsset, borrower, collateral, amount); } else { _liquidateERC( borrowedAsset, underlyingAsset, borrower, collateral, amount ); } //transfer seized collateral to liquidator collateralSeized = _transferSeizedCollateral( collateral, collateralInitialbalance ); emit AccountLiquidated( borrower, msg.sender, collateral, collateralSeized ); } function _liquidateETH( address borrowedAsset, address borrower, address collateral, uint256 amount ) internal { //liquidate ICEther(borrowedAsset).liquidateBorrow.value(amount)( borrower, collateral ); } function _liquidateERC( address borrowedAsset, address underlyingAsset, address borrower, address collateral, uint256 amount ) internal { //approve IERC20(underlyingAsset).approve(borrowedAsset, amount); //liquidate require( ICToken(borrowedAsset).liquidateBorrow( borrower, amount, collateral ) == 0, "Error in repay" ); } function _transferSeizedCollateral( address collateral, uint256 collateralInitialbalance ) internal returns (uint256 collateralSeized) { uint256 collateralFinalbalance = IERC20(collateral).balanceOf( address(this) ); collateralSeized = collateralFinalbalance.sub(collateralInitialbalance); IERC20(collateral).transfer(msg.sender, collateralSeized); } }
amount in underlying asset termsrepay
function repayBorrowedAsset( address borrower, address cToken, uint256 repayAmount ) public { address underlyingToken = ICToken(cToken).underlying(); require( balance[msg.sender][underlyingToken] >= repayAmount, "Insufficient deposit" ); balance[msg.sender][underlyingToken] = balance[msg .sender][underlyingToken] .sub(repayAmount); if (borrower == msg.sender) { _repayBorrow(underlyingToken, cToken, repayAmount); _repayBorrowBehalf(underlyingToken, borrower, cToken, repayAmount); } emit AmountRepaid(borrower, msg.sender, repayAmount); }
12,869,259
//SPDX-License-Identifier: MIT pragma solidity 0.7.0; import "./ClaimUtils.sol"; import "./interfaces/IIouUtils.sol"; /// @title Contract where the IOU logic of the API3 pool is implemented contract IouUtils is ClaimUtils, IIouUtils { /// @param api3TokenAddress Address of the API3 token contract /// @param epochPeriodInSeconds Length of epochs used to quantize time /// @param firstEpochStartTimestamp Starting timestamp of epoch #1 constructor( address api3TokenAddress, uint256 epochPeriodInSeconds, uint256 firstEpochStartTimestamp ) public ClaimUtils( api3TokenAddress, epochPeriodInSeconds, firstEpochStartTimestamp ) {} /// @notice Creates an IOU record /// @param userAddress User address that will receive the IOU payment if /// redemptionCondition is met /// @param amountInShares Amount that will be paid in shares if /// redemptionCondition is met /// @param claimId Claim ID /// @param redemptionCondition Claim status needed for payment to be made function createIou( address userAddress, uint256 amountInShares, bytes32 claimId, ClaimStatus redemptionCondition ) internal { bytes32 iouId = keccak256(abi.encodePacked(noIous, this)); noIous = noIous.add(1); ious[iouId] = Iou({ userAddress: userAddress, amountInShares: amountInShares, claimId: claimId, redemptionCondition: redemptionCondition }); emit IouCreated( iouId, userAddress, amountInShares, claimId, redemptionCondition ); } /// @notice Redeems an IOU /// @dev If the claim is finalized and redemptionCondition is not met, the /// IOU gets deleted without the user getting paid /// @param iouId IOU ID function redeem(bytes32 iouId) external override { Iou memory iou = ious[iouId]; ClaimStatus claimStatus = claims[iou.claimId].status; require(claimStatus != ClaimStatus.Pending, "IOU not redeemable yet"); if (claimStatus == iou.redemptionCondition) { uint256 amountInTokens = convertFromShares(iou.amountInShares); if (iou.redemptionCondition == ClaimStatus.Denied) { // While unpooling with an active claim, the user is given an // IOU for the amount they would pay out to the claim, and this // amount is left in the pool as "ghost shares" to pay out the // active claim if necessary. If the claim is denied and the // IOU is being redeemed, these ghost shares should be removed. totalShares = totalShares.sub(iou.amountInShares); totalGhostShares = totalGhostShares.sub(iou.amountInShares); totalPooled = totalPooled.sub(amountInTokens); } balances[iou.userAddress] = balances[iou.userAddress].add( amountInTokens ); emit IouRedeemed(iouId, amountInTokens); } else { emit IouDeleted(iouId); } delete ious[iouId]; } }
Redeems an IOU If the claim is finalized and redemptionCondition is not met, the IOU gets deleted without the user getting paid iouId IOU ID While unpooling with an active claim, the user is given an IOU for the amount they would pay out to the claim, and this amount is left in the pool as "ghost shares" to pay out the active claim if necessary. If the claim is denied and the IOU is being redeemed, these ghost shares should be removed.
function redeem(bytes32 iouId) external override { Iou memory iou = ious[iouId]; ClaimStatus claimStatus = claims[iou.claimId].status; require(claimStatus != ClaimStatus.Pending, "IOU not redeemable yet"); if (claimStatus == iou.redemptionCondition) { uint256 amountInTokens = convertFromShares(iou.amountInShares); if (iou.redemptionCondition == ClaimStatus.Denied) { totalShares = totalShares.sub(iou.amountInShares); totalGhostShares = totalGhostShares.sub(iou.amountInShares); totalPooled = totalPooled.sub(amountInTokens); } balances[iou.userAddress] = balances[iou.userAddress].add( amountInTokens ); emit IouRedeemed(iouId, amountInTokens); emit IouDeleted(iouId); } delete ious[iouId]; }
15,794,488
./full_match/5/0x2743d6F0fb1E4CCb768D4530841d35dC44C59789/sources/contracts/extension/upgradeable/Permissions.sol
Checks `role` for `account`. Reverts with a message including the required role.
function _checkRole(bytes32 role, address account) internal view virtual { if (!_permissionsStorage()._hasRole[role][account]) { revert( string( abi.encodePacked( "Permissions: account ", TWStrings.toHexString(uint160(account), 20), " is missing role ", TWStrings.toHexString(uint256(role), 32) ) ) ); } }
11,603,045
./partial_match/1/0x4eA5424C393869505CBD7F8d802595328aAB89Fe/sources/Incentives.sol
Adds an exchange creating its associated data structures init epoch
function addExchange(address _exchange, address _liquidityToken) public onlyExchangeFactoryOrVotingSystem { require(exchangeDataByExchangeAddress[_exchange].exchangeAddress == address(0), "exchange should not exists"); allExchangeAddresses.push(_exchange); ExchangeData storage data = exchangeDataByExchangeAddress[_exchange]; data.exchangeAddress = _exchange; data.liquidityToken = ERC20Snapshot(_liquidityToken); Epoch storage epoch = data.epochEntries[epochCount]; epoch.isActiveEpoch = true; epoch.snapShotId = data.liquidityToken.snapshot(); }
2,610,756
./full_match/5/0xfD88ce3683b92D1472E11442eAAC0c7Bf5fdFd2c/sources/contracts/liq.sol
Internal function to burn liquidity shares
function _burn(address _from, uint256 _amount) private { userLiquidity[_from] -= _amount; totalLiquidity -= _amount; }
1,871,937
pragma solidity ^0.4.24; import "contracts/Storage.sol"; contract MultiSignAdmin is Pausable, Administratable, UserContract { /* * Constants */ uint256 constant public maxBankCount = 50; /* * events */ event BankAddition(address indexed bank); event BankRemoval(address indexed bank); event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event RequirementChange(uint256 required); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); // This notifies clients about the amount mint event Mint(address indexed to, uint256 value); /* * Storage */ Balance internal _balances; address[] public alliance; mapping (address => bool) public inAlliance; mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bool isMint; bool executed; } /* * modifiers */ modifier validRequirement(uint256 bankCount, uint256 _required) { require(bankCount <= maxBankCount && _required <= bankCount && _required != 0 && bankCount != 0); _; } modifier bankNotExist(address bank) { require(!inAlliance[bank]); _; } modifier bankExists(address bank) { require(inAlliance[bank]); _; } modifier transactionExists(uint256 transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint256 transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint256 transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint256 transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } constructor( Balance _balanceContract, Blacklist _blacklistContract, Verified _verifiedListContract, address[] _banks, uint256 _required ) UserContract(_blacklistContract, _verifiedListContract) validRequirement(_banks.length, _required) public { _balances = _balanceContract; for (uint256 i=0; i<_banks.length; i++) { require(!inAlliance[_banks[i]] && _banks[i] != 0); inAlliance[_banks[i]] = true; } alliance = _banks; required = _required; } /// @dev Allows to add a new bank. Transaction has to be sent by owner. /// @param bank Address of new bank. function addBank(address bank) onlyOwner bankNotExist(bank) notNull(bank) validRequirement(alliance.length + 1, required) public { inAlliance[bank] = true; alliance.push(bank); emit BankAddition(owner); } /// @dev Allows to remove a bank. Transaction has to be sent by owner. /// @param bank Address of bank. function removeBank(address bank) onlyOwner bankExists(bank) public { inAlliance[bank] = false; for (uint256 i=0; i<alliance.length - 1; i++) if (alliance[i] == bank) { alliance[i] = alliance[alliance.length - 1]; break; } alliance.length -= 1; if (required > alliance.length) changeRequirement(alliance.length); emit BankRemoval(owner); } /// @dev Allows to replace an bank with a new bank. Transaction has to be sent by owner. /// @param bank Address of bank to be replaced. /// @param newBank Address of new bank. function replaceBank(address bank, address newBank) onlyOwner bankExists(bank) bankNotExist(newBank) public { for (uint256 i=0; i<alliance.length; i++) if (alliance[i] == bank) { alliance[i] = newBank; break; } inAlliance[bank] = false; inAlliance[newBank] = true; emit BankRemoval(bank); emit BankAddition(newBank); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint256 _required) onlyOwner validRequirement(alliance.length, _required) public { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a mint transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function proposeMint(address destination, uint256 value) bankExists(msg.sender) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, true); confirmTransaction(transactionId); } /// @dev Allows an owner to submit and confirm a burnFrom transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @return Returns transaction ID. function proposeBurn(address destination, uint256 value) bankExists(msg.sender) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, false); confirmTransaction(transactionId); } /// @dev Allows a bank to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint256 transactionId) bankExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) public { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows a bank to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint256 transactionId) bankExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) public { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint256 transactionId) bankExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) public { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; bool success = true; if (txn.isMint) { success = _mint(txn.destination, txn.value); } else { success = _burnFrom(txn.destination, txn.value); } if (success) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i=0; i<alliance.length; i++) { if (confirmations[transactionId][alliance[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param isMint true if calling Mint, false if calling BurnFrom. /// @return Returns transaction ID. function addTransaction(address destination, uint256 value, bool isMint) notNull(destination) internal returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, isMint: isMint, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i=0; i<alliance.length; i++) if (confirmations[transactionId][alliance[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint256 count) { for (uint256 i=0; i<transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of banks. /// @return List of bank addresses. function getAlliance() public view returns (address[]) { return alliance; } /// @dev Returns array with bank addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of bank addresses. function getConfirmations(uint256 transactionId) public view returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](alliance.length); uint256 count = 0; uint256 i; for (i=0; i<alliance.length; i++) if (confirmations[transactionId][alliance[i]]) { confirmationsTemp[count] = alliance[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint256 from, uint256 to, bool pending, bool executed) public view returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint256 count = 0; uint256 i; for (i=0; i<transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function _burnFrom(address _from, uint256 _value) whenNotPaused internal returns (bool success) { require(_balances.balanceOf(_from) >= _value); // Check if the targeted balance is enough _balances.subBalance(_from, _value); // Subtract from the targeted balance _balances.subTotalSupply(_value); emit Burn(_from, _value); return true; } /** * Add `_amount` tokens to the pool and to the `_to` address' balance * * @param _to the address that will receive the given amount of tokens * @param _amount the amount of tokens it will receive */ function _mint(address _to, uint256 _amount) whenNotPaused internal returns (bool success) { _balances.addBalance(_to, _amount); _balances.addTotalSupply(_amount); emit Mint(_to, _amount); return true; } }
Returns array with bank addresses, which confirmed transaction. transactionId Transaction ID. return Returns array of bank addresses.
function getConfirmations(uint256 transactionId) public view returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](alliance.length); uint256 count = 0; uint256 i; for (i=0; i<alliance.length; i++) if (confirmations[transactionId][alliance[i]]) { confirmationsTemp[count] = alliance[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; }
5,414,990
// Reference from https://github.com/lition-blockchain/syndicate-loan-use-case/blob/master/contracts/SynLoan.sol pragma solidity ^0.5.2; // necessary because some functions return structs pragma experimental ABIEncoderV2; /* Contract for Syndicate Loan MVP by Lition Technologie AG - www.lition.io version 0.2.3.5 creator: Marcel Jackisch */ contract SynLoanData { uint public loanId; // A unique number that increments with every newly created loan LoanData[] public loans; struct LoanData { uint id; // Loan ID string name; // Name of the Loan uint revisionNumber; // Shall increment with every update to the loan address registeringParty; // Party who registered the loan. Possible unnecessary because of mapping loanToRegistrar string dataString; // formerly "purpose", now general data string uint regTime; // UNIX Timestamp mapping (address => uint) userToId; // Gets local user id belonging (mapped to) an address in loan uint[] loanAmounts; // corresponding to participants bool[] approvalStatus; // Array to store approvals address[] userList; uint8 numOfUsers; } /* Struct user defines key data of participants such as banks and businesses */ struct userData { string name; string role; // Borrower or Lender address account; } // Public array of all participants in dApp/Smart Contract (maybe unnecessary) userData[] public users; // Dictionary to find account data mapping (address => userData) addressToUserData; // Necessary to require user can only added to a loan once mapping (address => mapping (uint => bool)) addressAssociated; // Map a loan id to an account address of registrating user mapping (uint => address) loanToRegistrar; // counts the amount of loans belonging to the address mapping (address => uint) userLoanCount; /* Modifier to check that sender is the registrar of the loan */ modifier onlyRegistrar(uint _loanId) { require(msg.sender == loanToRegistrar[_loanId], "Only the owner of the loan has permission for this action"); _; } /* Modifier to check if sender is participant of a loan */ modifier onlyParticipant (uint _loanId) { require(loans[_loanId].userToId[msg.sender] != 0 || loanToRegistrar[_loanId] == msg.sender, "You are not part of this loan"); _; } function createLoan (string memory _name, string memory _dataString) public { loanToRegistrar[loanId] = msg.sender; // Store the address of the user in mapping userLoanCount[msg.sender]++; // necessary for array to count loans registered by user // create LoanData instance in memory, later populate array LoanData memory ln; ln.id = loanId; ln.name = _name; ln.revisionNumber = 0; ln.registeringParty = msg.sender; ln.dataString = _dataString; ln.regTime = now; loans.push(ln); // Add loan creator himself/herself addUserToLoan(loanId, msg.sender); loanId++; // Increment unique number } /* Update Loan Data, increment version / revision number Here, all the other data like loan amount, start date and other conditions shall be filled */ function updateLoan(uint _loanId, string memory _name, string memory _dataString, uint _loanAmount) public onlyParticipant(_loanId) { loans[_loanId].name = _name; loans[_loanId].dataString = _dataString; // Save specified loan amount in array corresponding to user index uint userId = loans[_loanId].userToId[msg.sender]; loans[_loanId].loanAmounts[userId] = _loanAmount; loans[_loanId].revisionNumber++; resetApprovals(_loanId); } /* Functionality to delete loan */ function deleteLoan(uint _id) public onlyRegistrar(_id) { delete loans[_id]; } /* Approves Loan: each participant of Loan can give his approval */ function approveLoan(uint _loanId, uint _revisionNumber) public { uint userId = loans[_loanId].userToId[msg.sender]; require(loans[_loanId].revisionNumber == _revisionNumber, "Versions of the loan do not match"); loans[_loanId].approvalStatus[userId] = true; } /* Function to reset approvals called after loan has been updated */ function resetApprovals(uint _loanId) internal { uint n = loans[_loanId].approvalStatus.length; for (uint i=0; i < n; i++) { loans[_loanId].approvalStatus[i] = false; } } /* Function to add new users to a loan, checks if user has been added before */ function addUserToLoan (uint _loanId, address _account) public onlyRegistrar(_loanId) returns (uint){ // The following three lines check that the zero-address cant be added and prohibit double registration require(_account != address(0)); require(addressAssociated[_account][_loanId] == false, "User already exists in loan"); addressAssociated[_account][_loanId] = true; userLoanCount[_account]++; uint userNum = loans[_loanId].numOfUsers++; // Adds user to mapping of loan (analog to incremented numOfUsers) loans[_loanId].userToId[_account] = userNum; // Pushes address to userList array (to retrieve all users, iterate) loans[_loanId].userList.push(_account); // Let size of arrays that correspond with users grow in size loans[_loanId].approvalStatus.length++; loans[_loanId].loanAmounts.length++; return userNum; } /* Self-Registration of a user account */ function selfRegistration (string memory _name, string memory _role) public { // Conditions to ensure no ghost users are registered require(bytes (_name).length > 0, "Name must be specified"); require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower"); require(bytes (addressToUserData[msg.sender].name).length == 0, "User has been registered before"); // Consider if populating array is necessary userData memory u; u.name = _name; u.role = _role; u.account = msg.sender; users.push(u); // Self-registration: Mapping ---- (-1??) addressToUserData[msg.sender] = u; } /* Registration of a user account by _anyone_ (public) */ function userRegistration (string memory _name, string memory _role, address _account) public { // Conditions to ensure no ghost users are registered require(bytes (_name).length > 0, "Name must be specified"); require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower"); require(bytes (addressToUserData[_account].name).length == 0, "User has been registered before"); // Consider if populating array is necessary userData memory u; u.name = _name; u.role = _role; u.account = _account; users.push(u); addressToUserData[_account] = u; } /* Function to let users change their data after it has been created */ function editUserData(string memory _name, string memory _role) public { require(keccak256(abi.encode(_role)) == keccak256(abi.encode("lender")) || keccak256(abi.encode(_role)) == keccak256(abi.encode("borrower")), "Role must match 'lender' or 'borrower"); addressToUserData[msg.sender].role = _role; addressToUserData[msg.sender].name = _name; // Array update necessary uint memory index; userData memory u; for (uint i = 0; i < users.length; i++) { if (users[i].address == msg.sender) { index = i; } } } /* Helper function to retrieve [mapping userLoanCount] */ function getUserLoanCount(address _addr) public view returns(uint) { return userLoanCount[_addr]; } /* Helper function to retrieve [mapping loanToRegistrar] */ function getloanToRegistrar(uint _loanId) public view returns(address) { return loanToRegistrar[_loanId]; } /* Helper function to retrieve UserId from mapping inside struct */ function getUserToId(uint256 _loanId, address _address) public view returns (uint256) { return loans[_loanId].userToId[_address]; } /* Helper function to retrieve data belonging to an address */ function getUserDataByAddr(address _account) public view returns(userData memory) { return addressToUserData[_account]; } /* Helper function to retrieve List of all registered Addresses in Loan */ function getUsersInLoan (uint256 _loanId) public view returns (address[] memory, uint) { address[] memory addrArr = loans[_loanId].userList; uint userCount = loans[_loanId].numOfUsers; return (addrArr, userCount); } /* Helper function to retrieve approval status array */ function getApprovalStatus(uint256 _loanId) public view returns (bool[] memory) { bool[] memory array = loans[_loanId].approvalStatus; // approvalStatus is a bool array in a struct array return array; } /* Helper function to retrieve the loan amounts of the users from struct */ function getLoanAmounts(uint256 _loanId) public view returns (uint[] memory) { uint[] memory array = loans[_loanId].loanAmounts; return array; } /* Get the length of the loan array */ function getArrLength() public view returns (uint256) { return (loans.length); } /* Get the length of the user array */ function getUserArrLength() public view returns (uint256) { return (users.length); } /* The function should return an array with all the loans the user is involved in, disregarding any other permissioning like read-write requests Important to log all the loans by the user As of now, only the registrar mapping is applied, a loan belonging to multiple users cannot be created yet Info: mapping (uint => address) loanToRegistrar; */ function getLoansByUser(address _user) external view returns(uint[] memory) { // Create a new array with as many entries as Loans belong to the user uint[] memory result = new uint[](userLoanCount[_user]); uint counter = 0; // Iterate through loanToRegistrar mapping and check if equals address, then sum up for (uint i = 0; i < loans.length; i++) { if (loanToRegistrar[i] == _user) { result[counter] = i; counter++; } // Check if user is part of the loan but not registrar else { address[] memory _userArr = loans[i].userList; for (uint c = 0; c < _userArr.length; c++ ) { if (_userArr[c] == _user) { result[counter] = i; counter++; } } } } return result; } }
/ Save specified loan amount in array corresponding to user index
function updateLoan(uint _loanId, string memory _name, string memory _dataString, uint _loanAmount) public onlyParticipant(_loanId) { loans[_loanId].name = _name; loans[_loanId].dataString = _dataString; uint userId = loans[_loanId].userToId[msg.sender]; loans[_loanId].loanAmounts[userId] = _loanAmount; loans[_loanId].revisionNumber++; resetApprovals(_loanId); }
12,967,641
./full_match/3/0xf33Cd0e760004229B6aD0b0fC9e3744bd817FE81/sources/Localhost.sol
Org: Send BGV Request to customeremit NewKYCRequest(_uAddress, msg.sender);
function sendBgvRequest(address _uAddress) external registeredOrg(msg.sender) returns (bool success) { require(users[_uAddress].state == State.Approved, "Please Ask User to initiate verification request first."); kycRequests[_uAddress][msg.sender] = BGVRequest(State.Pending, false, false, false , false, false, false, false, false); return true; }
8,229,492
/** * OpenZepplin contracts contained within are licensed under an MIT License. * * The MIT License (MIT) * * Copyright (c) 2016-2021 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * SPDX-License-Identifier: MIT */ // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/security/ReentrancyGuard.sol pragma solidity ^0.8.0; abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } 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: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Strings.sol pragma solidity ^0.8.0; library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 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); } 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); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Context.sol pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/Address.sol pragma solidity ^0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 ) internal pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } pragma solidity ^0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name = "Igor - EtherCats.io"; // Token symbol string private _symbol = "IGOR"; // 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; function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : "ipfs://QmY2RtPNfCYyJJW8CtbNWLs3GGSaUus5vG38g4kRZ5Ci7k"; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } 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); } 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); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not owned"); 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); } function snipe( address from, address to, uint256 tokenId ) internal virtual { _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); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } //Igor's Manifest is an EtherCats production. Igor was illustrated and animated by Nadia Khuzina. The principle concept was developed by Woody Deck. The contract was written by Woody Deck and Edvard Gzraryan. Special thanks to Vitalik Buterin for his inspiration in challenging economic dogma. contract IgorsManifest is ERC721, ReentrancyGuard { address public contractOwner; uint256 public snipeStep; uint256 public snipePrice; bool public snipeable; uint256 public blockTimerStartTime; string igorsHash; event Snipe(address indexed owner, uint256 price, uint256 step, uint256 blockTimestamp); event ExtendLeasehold(uint256 blockTimestamp); event DecreaseSnipeStep(uint256 price, uint256 step, uint256 blockTimestamp); constructor() { contractOwner = msg.sender; _safeMint(msg.sender, 1, ""); //Igor is minted as token ID number 1, and the contractOwner owns it initially. snipeStep = 0; snipePrice = snipePriceTable(snipeStep); snipeable = true; blockTimerStartTime = block.timestamp; igorsHash = "QmSGsx5Cs1zLxmMX8YjvGx1x1vYn47jzuFKy13yhM4S61q"; } //This is a lookup table to determine the cost to snipe Igor from someone. function snipePriceTable(uint256 _snipeStep) internal pure returns(uint256 _snipePrice) { if (_snipeStep == 0) return 0.1 * 10 ** 18; else if (_snipeStep == 1) return 0.15 * 10 ** 18; else if (_snipeStep == 2) return 0.21 * 10 ** 18; else if (_snipeStep == 3) return 0.28 * 10 ** 18; else if (_snipeStep == 4) return 0.36 * 10 ** 18; else if (_snipeStep == 5) return 0.45 * 10 ** 18; else if (_snipeStep == 6) return 0.55 * 10 ** 18; else if (_snipeStep == 7) return 0.66 * 10 ** 18; else if (_snipeStep == 8) return 0.78 * 10 ** 18; else if (_snipeStep == 9) return 1 * 10 ** 18; else if (_snipeStep == 10) return 1.5 * 10 ** 18; else if (_snipeStep == 11) return 2.2 * 10 ** 18; else if (_snipeStep == 12) return 3 * 10 ** 18; else if (_snipeStep == 13) return 4 * 10 ** 18; else if (_snipeStep == 14) return 6 * 10 ** 18; else if (_snipeStep == 15) return 8.5 * 10 ** 18; else if (_snipeStep == 16) return 12 * 10 ** 18; else if (_snipeStep == 17) return 17 * 10 ** 18; else if (_snipeStep == 18) return 25 * 10 ** 18; else if (_snipeStep == 19) return 35 * 10 ** 18; else if (_snipeStep == 20) return 47 * 10 ** 18; else if (_snipeStep == 21) return 60 * 10 ** 18; else if (_snipeStep == 22) return 75 * 10 ** 18; else if (_snipeStep == 23) return 92 * 10 ** 18; else if (_snipeStep == 24) return 110 * 10 ** 18; else if (_snipeStep == 25) return 130 * 10 ** 18; else if (_snipeStep == 26) return 160 * 10 ** 18; else if (_snipeStep == 27) return 200 * 10 ** 18; else if (_snipeStep == 28) return 250 * 10 ** 18; else if (_snipeStep == 29) return 310 * 10 ** 18; else if (_snipeStep == 30) return 380 * 10 ** 18; else if (_snipeStep == 31) return 460 * 10 ** 18; else if (_snipeStep == 32) return 550 * 10 ** 18; else if (_snipeStep == 33) return 650 * 10 ** 18; else if (_snipeStep == 34) return 760 * 10 ** 18; } modifier onlyIgorOwner() { require(msg.sender == ownerOf(1), "Sender is not the owner of Igor."); _; } function snipeIgor() external payable nonReentrant { require(msg.sender != ownerOf(1), "You cannot snipe Igor from the address that already owns him."); require(msg.value == snipePrice, "The amount sent did not match the current snipePrice."); require(snipeable == true, "Sniping is permanently disabled. Igor is owned as a freehold now."); address tokenOwner = ownerOf(1); //If the snipeStep is 0, then all proceeds go to the owner. if (snipeStep == 0) { snipeStep++; snipePrice = snipePriceTable(snipeStep); snipe(tokenOwner, msg.sender, 1); (bool sent,) = payable(tokenOwner).call{ value: msg.value }(""); require(sent, "Failed to send Ether."); } else { //Else is all cases after Step 0. uint256 etherCatsRoyalty = (msg.value - snipePriceTable(snipeStep - 1)) * 25 / 100; uint256 payment = msg.value - etherCatsRoyalty; if (snipeStep < 34) { snipeStep++; snipePrice = snipePriceTable(snipeStep); } //Automatically stop sniping if Igor is sniped on Step 33. if (snipeStep == 34) { snipeable = false; } snipe(tokenOwner, msg.sender, 1); (bool paymentSent,) = payable(tokenOwner).call{ value: payment }(""); require(paymentSent, "Failed to send Ether."); (bool royaltySent,) = payable(contractOwner).call{ value: etherCatsRoyalty }(""); require(royaltySent, "Failed to send Ether."); } blockTimerStartTime = block.timestamp; emit Snipe(msg.sender, snipePrice, snipeStep, blockTimerStartTime); } //This option disables sniping permanently. It will behave like a normal ERC721 after this function is triggered. It can only be called by Igor's owner. function permanentlyStopSniping() external payable onlyIgorOwner { require(snipeStep <= 20, "Igor can only be bought out on snipe steps before Step 21."); require(msg.value == 141 * 10 ** 18, "The amount sent did not match the freehold option amount."); require(snipeable == true, "Cannot disable sniping twice. Igor is already not snipeable."); snipeable = false; (bool sent,) = payable(contractOwner).call{ value: msg.value }(""); require(sent, "Failed to send Ether."); } //To prevent people from reducing the snipe step, you must pay 1/1000th (0.1%) tax to the creator every two weeks. Activating this function early or multiple times does not result in time accumulating. It will always reset the countdown clock back to 1209600 seconds (two weeks). function extendLeasehold() external payable onlyIgorOwner { require(snipeStep >= 1, "You cannot extend the leasehold timer when it is step zero."); require(msg.value == snipePriceTable(snipeStep-1) / 1000, "The price to extend is 1/1000th of the current value, or the snipe step minus 1"); require(snipeable == true, "Cannot extend. Igor is not snipeable anymore, sorry."); blockTimerStartTime = block.timestamp; (bool sent,) = payable(contractOwner).call{ value: msg.value }(""); require(sent, "Failed to send Ether."); emit ExtendLeasehold(blockTimerStartTime); } //If the owner after 1209600 seconds (two weeks) has not paid the extension tax, then anyone can reduce the snipeStep by 1. function decreaseSnipeStep() external { require(block.timestamp - blockTimerStartTime > 1209600, "You cannot reduce the snipe step until after the lease is up."); require(snipeStep >= 1, "You cannot reduce the snipe step when it is at zero."); require(snipeStep < 34, "You cannot reduce the snipe step once it reaches step 34."); require(snipeable == true, "Igor is not snipeable anymore, sorry."); snipeStep--; snipePrice = snipePriceTable(snipeStep); blockTimerStartTime = block.timestamp; emit DecreaseSnipeStep(snipePrice, snipeStep, blockTimerStartTime); } //This function is for site owners to vet that Igor is only shown by the Ethereum address that owns him. This is conceptual, and only facilitates the possibility of restricting PFP NFTs from being displayed by accounts that do not own the NFT. It is up to a site to implement such a process on its own. It is not mandated by the terms of this contract. Reputable sites concerned about security will never store or even ask you to create a password. Reputable sites will require Web3 authentication for logins. Adding PFP avatar restrictions is trivial after adopting Web3 for authentication. function pfpOwner() external view returns (address igorsOwner, string memory igorsIPFSHash){ return (ownerOf(1), igorsHash); } //There's only one Igor. Some frontends may look for this optional ERC721 implementation. function totalSupply() public pure returns (uint256) { return 1; } }
If the snipeStep is 0, then all proceeds go to the owner.Else is all cases after Step 0.Automatically stop sniping if Igor is sniped on Step 33.
function snipeIgor() external payable nonReentrant { require(msg.sender != ownerOf(1), "You cannot snipe Igor from the address that already owns him."); require(msg.value == snipePrice, "The amount sent did not match the current snipePrice."); require(snipeable == true, "Sniping is permanently disabled. Igor is owned as a freehold now."); address tokenOwner = ownerOf(1); if (snipeStep == 0) { snipeStep++; snipePrice = snipePriceTable(snipeStep); snipe(tokenOwner, msg.sender, 1); require(sent, "Failed to send Ether."); uint256 etherCatsRoyalty = (msg.value - snipePriceTable(snipeStep - 1)) * 25 / 100; uint256 payment = msg.value - etherCatsRoyalty; if (snipeStep < 34) { snipeStep++; snipePrice = snipePriceTable(snipeStep); } if (snipeStep == 34) { snipeable = false; } snipe(tokenOwner, msg.sender, 1); require(paymentSent, "Failed to send Ether."); require(royaltySent, "Failed to send Ether."); } blockTimerStartTime = block.timestamp; emit Snipe(msg.sender, snipePrice, snipeStep, blockTimerStartTime); }
1,510,556
./partial_match/1/0xFd30e99388C4e8110054b7012811B0DF042E51D0/sources/SharedRevenueMerkle.sol
Function to cancel Distribution
function cancelDistribution(uint256 distributionId) external onlyOwner { Distribution storage dist = distributions[distributionId]; require( block.timestamp > dist.expirationTime, "Distribution still active" ); require(!dist.isCancelled, "Distribution is already cancelled"); lockedFunds -= dist.amountLocked; dist.isCancelled = true; emit DistributionCanceled(distributionId, dist.amountLocked, dist.totalAmount); }
4,457,040
/* Copyright 2020 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { I_Solo } from "../../external/dydx/I_Solo.sol"; /** * @title Test_Solo * @author dYdX * * Interface for calling the Solo margin smart contract. */ /* solium-disable-next-line camelcase */ contract Test_Solo is I_Solo { // ============ Test Data ============ mapping(address => bool) internal _GLOBAL_OPERATORS_; mapping(address => mapping(address => bool)) internal _LOCAL_OPERATORS_; mapping(uint256 => address) public _TOKEN_ADDRESSES_; // ============ Test Data Setter Functions ============ function setIsLocalOperator( address owner, address operator, bool approved ) external returns (bool) { return _LOCAL_OPERATORS_[owner][operator] = approved; } function setIsGlobalOperator( address operator, bool approved ) external returns (bool) { return _GLOBAL_OPERATORS_[operator] = approved; } function setTokenAddress( uint256 marketId, address tokenAddress ) external { _TOKEN_ADDRESSES_[marketId] = tokenAddress; } // ============ Getter Functions ============ /** * Return true if a particular address is approved as an operator for an owner's accounts. * Approved operators can act on the accounts of the owner as if it were the operator's own. * * @param owner The owner of the accounts * @param operator The possible operator * @return True if operator is approved for owner's accounts */ function getIsLocalOperator( address owner, address operator ) external view returns (bool) { return _LOCAL_OPERATORS_[owner][operator]; } /** * Return true if a particular address is approved as a global operator. Such an address can * act on any account as if it were the operator's own. * * @param operator The address to query * @return True if operator is a global operator */ function getIsGlobalOperator( address operator ) external view returns (bool) { return _GLOBAL_OPERATORS_[operator]; } /** * @notice Get the ERC20 token address for a market. * * @param marketId The market to query * @return The token address */ function getMarketTokenAddress( uint256 marketId ) public view returns (address) { return _TOKEN_ADDRESSES_[marketId]; } // ============ State-Changing Functions ============ /** * @notice The main entry-point to Solo that allows users and contracts to manage accounts. * Takes one or more actions on one or more accounts. The msg.sender must be the owner or * operator of all accounts except for those being liquidated, vaporized, or traded with. * One call to operate() is considered a singular "operation". Account collateralization is * ensured only after the completion of the entire operation. * * @param accounts A list of all accounts that will be used in this operation. Cannot contain * duplicates. In each action, the relevant account will be referred to by its * index in the list. * @param actions An ordered list of all actions that will be taken in this operation. The * actions will be processed in order. */ function operate( I_Solo.AccountInfo[] memory accounts, I_Solo.ActionArgs[] memory actions ) public // public instead of external to avoid UnimplementedFeatureError { // Expect exactly one account and one action. require(accounts.length == 1, "Expected one account"); require(actions.length == 1, "Expected one action"); I_Solo.AccountInfo memory account = accounts[0]; I_Solo.ActionArgs memory action = actions[0]; // Get the ERC20 token. IERC20 token = IERC20(getMarketTokenAddress(action.primaryMarketId)); // Compare account and action parameters. require(account.number == action.accountId, "Account ID mismatch"); // Check amount parameters. I_Solo.AssetAmount memory amount = action.amount; require( amount.denomination == I_Solo.AssetDenomination.Wei, "Expected amount denomination to be Wei" ); uint256 amountToTransfer; if (amount.ref == I_Solo.AssetReference.Delta) { amountToTransfer = amount.value; } else { require(amount.value == 0, "When using AssetReference.Target, expect value to be zero"); require( action.actionType == I_Solo.ActionType.Withdraw, "When using AssetReference.Target, expect action to be withdrawal" ); // Assume that the whole token balance belongs to the sender. amountToTransfer = token.balanceOf(address(this)); } if (action.actionType == I_Solo.ActionType.Withdraw) { require(!amount.sign, "Expected amount to be negative"); // Perform token transfer. token.transfer(action.otherAddress, amountToTransfer); } else if (action.actionType == I_Solo.ActionType.Deposit) { require(amount.sign, "Expected amount to be positive"); // Perform token transfer. token.transferFrom(action.otherAddress, address(this), amountToTransfer); } else { revert("Expected action type to be Withdraw or Deposit"); } } }
Get the ERC20 token address for a market. marketId The market to query return The token address/
function getMarketTokenAddress( uint256 marketId ) public view returns (address) { return _TOKEN_ADDRESSES_[marketId]; }
7,318,715
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/ProtoBufRuntime.sol"; import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/GoogleProtobufAny.sol"; import "@hyperledger-labs/yui-ibc-solidity/contracts/core/types/gogoproto/gogo.sol"; import "./Auth.sol"; library PacketData { //struct definition struct Data { Header.Data header; bytes payload; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_payload(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Header.Data memory x, uint256 sz) = _decode_Header(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_payload( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.payload = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Header(uint256 p, bytes memory bs) internal pure returns (Header.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Header.Data memory r, ) = Header._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Header._encode_nested(r.header, pointer, bs); if (r.payload.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.payload, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Header._estimate(r.header)); e += 1 + ProtoBufRuntime._sz_lendelim(r.payload.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.payload.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Header.store(input.header, output.header); output.payload = input.payload; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PacketData library Acknowledgement { //struct definition struct Data { bool is_success; bytes result; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_is_success(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_result(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_is_success( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bool x, uint256 sz) = ProtoBufRuntime._decode_bool(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.is_success = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_result( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.result = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.is_success != false) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_bool(r.is_success, pointer, bs); } if (r.result.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.result, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + 1; e += 1 + ProtoBufRuntime._sz_lendelim(r.result.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.is_success != false) { return false; } if (r.result.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.is_success = input.is_success; output.result = input.result; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Acknowledgement library Header { //struct definition struct Data { HeaderField.Data[] fields; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_fields(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.fields = new HeaderField.Data[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_fields(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_fields( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (HeaderField.Data memory x, uint256 sz) = _decode_HeaderField(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.fields[r.fields.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_HeaderField(uint256 p, bytes memory bs) internal pure returns (HeaderField.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (HeaderField.Data memory r, ) = HeaderField._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.fields.length != 0) { for(i = 0; i < r.fields.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += HeaderField._encode_nested(r.fields[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.fields.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(HeaderField._estimate(r.fields[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.fields.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.fields.length; i1++) { output.fields.push(input.fields[i1]); } } //array helpers for Fields /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addFields(Data memory self, HeaderField.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ HeaderField.Data[] memory tmp = new HeaderField.Data[](self.fields.length + 1); for (uint256 i = 0; i < self.fields.length; i++) { tmp[i] = self.fields[i]; } tmp[self.fields.length] = value; self.fields = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Header library HeaderField { //struct definition struct Data { string key; bytes value; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (bytes(r.key).length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.key).length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.key).length != 0) { return false; } if (r.value.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library HeaderField library PacketDataCall { //struct definition struct Data { bytes tx_id; PacketDataCallResolvedContractTransaction.Data tx; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_tx_id(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_tx(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_tx_id( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.tx_id = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_tx( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (PacketDataCallResolvedContractTransaction.Data memory x, uint256 sz) = _decode_PacketDataCallResolvedContractTransaction(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.tx = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_PacketDataCallResolvedContractTransaction(uint256 p, bytes memory bs) internal pure returns (PacketDataCallResolvedContractTransaction.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (PacketDataCallResolvedContractTransaction.Data memory r, ) = PacketDataCallResolvedContractTransaction._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.tx_id.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.tx_id, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += PacketDataCallResolvedContractTransaction._encode_nested(r.tx, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.tx_id.length); e += 1 + ProtoBufRuntime._sz_lendelim(PacketDataCallResolvedContractTransaction._estimate(r.tx)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.tx_id.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.tx_id = input.tx_id; PacketDataCallResolvedContractTransaction.store(input.tx, output.tx); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PacketDataCall library PacketDataCallResolvedContractTransaction { //struct definition struct Data { GoogleProtobufAny.Data cross_chain_channel; Account.Data[] signers; bytes call_info; ReturnValue.Data return_value; GoogleProtobufAny.Data[] objects; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[6] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_cross_chain_channel(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_signers(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_call_info(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_return_value(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_objects(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.signers = new Account.Data[](counters[2]); r.objects = new GoogleProtobufAny.Data[](counters[5]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_cross_chain_channel(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_signers(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_call_info(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_return_value(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_objects(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_cross_chain_channel( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (GoogleProtobufAny.Data memory x, uint256 sz) = _decode_GoogleProtobufAny(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.cross_chain_channel = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signers( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Account.Data memory x, uint256 sz) = _decode_Account(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.signers[r.signers.length - counters[2]] = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_call_info( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.call_info = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_return_value( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ReturnValue.Data memory x, uint256 sz) = _decode_ReturnValue(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.return_value = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_objects( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (GoogleProtobufAny.Data memory x, uint256 sz) = _decode_GoogleProtobufAny(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.objects[r.objects.length - counters[5]] = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_GoogleProtobufAny(uint256 p, bytes memory bs) internal pure returns (GoogleProtobufAny.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (GoogleProtobufAny.Data memory r, ) = GoogleProtobufAny._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Account(uint256 p, bytes memory bs) internal pure returns (Account.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Account.Data memory r, ) = Account._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ReturnValue(uint256 p, bytes memory bs) internal pure returns (ReturnValue.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ReturnValue.Data memory r, ) = ReturnValue._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += GoogleProtobufAny._encode_nested(r.cross_chain_channel, pointer, bs); if (r.signers.length != 0) { for(i = 0; i < r.signers.length; i++) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += Account._encode_nested(r.signers[i], pointer, bs); } } if (r.call_info.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.call_info, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ReturnValue._encode_nested(r.return_value, pointer, bs); if (r.objects.length != 0) { for(i = 0; i < r.objects.length; i++) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += GoogleProtobufAny._encode_nested(r.objects[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(GoogleProtobufAny._estimate(r.cross_chain_channel)); for(i = 0; i < r.signers.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(Account._estimate(r.signers[i])); } e += 1 + ProtoBufRuntime._sz_lendelim(r.call_info.length); e += 1 + ProtoBufRuntime._sz_lendelim(ReturnValue._estimate(r.return_value)); for(i = 0; i < r.objects.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(GoogleProtobufAny._estimate(r.objects[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.signers.length != 0) { return false; } if (r.call_info.length != 0) { return false; } if (r.objects.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { GoogleProtobufAny.store(input.cross_chain_channel, output.cross_chain_channel); for(uint256 i2 = 0; i2 < input.signers.length; i2++) { output.signers.push(input.signers[i2]); } output.call_info = input.call_info; ReturnValue.store(input.return_value, output.return_value); for(uint256 i5 = 0; i5 < input.objects.length; i5++) { output.objects.push(input.objects[i5]); } } //array helpers for Signers /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addSigners(Data memory self, Account.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ Account.Data[] memory tmp = new Account.Data[](self.signers.length + 1); for (uint256 i = 0; i < self.signers.length; i++) { tmp[i] = self.signers[i]; } tmp[self.signers.length] = value; self.signers = tmp; } //array helpers for Objects /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addObjects(Data memory self, GoogleProtobufAny.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ GoogleProtobufAny.Data[] memory tmp = new GoogleProtobufAny.Data[](self.objects.length + 1); for (uint256 i = 0; i < self.objects.length; i++) { tmp[i] = self.objects[i]; } tmp[self.objects.length] = value; self.objects = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PacketDataCallResolvedContractTransaction library PacketAcknowledgementCall { //enum definition // Solidity enum definitions enum CommitStatus { COMMIT_STATUS_UNKNOWN, COMMIT_STATUS_OK, COMMIT_STATUS_FAILED } // Solidity enum encoder function encode_CommitStatus(CommitStatus x) internal pure returns (int32) { if (x == CommitStatus.COMMIT_STATUS_UNKNOWN) { return 0; } if (x == CommitStatus.COMMIT_STATUS_OK) { return 1; } if (x == CommitStatus.COMMIT_STATUS_FAILED) { return 2; } revert(); } // Solidity enum decoder function decode_CommitStatus(int64 x) internal pure returns (CommitStatus) { if (x == 0) { return CommitStatus.COMMIT_STATUS_UNKNOWN; } if (x == 1) { return CommitStatus.COMMIT_STATUS_OK; } if (x == 2) { return CommitStatus.COMMIT_STATUS_FAILED; } revert(); } //struct definition struct Data { PacketAcknowledgementCall.CommitStatus status; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_status(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_status( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PacketAcknowledgementCall.CommitStatus x = decode_CommitStatus(tmp); if (isNil(r)) { counters[1] += 1; } else { r.status = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.status) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_status = encode_CommitStatus(r.status); pointer += ProtoBufRuntime._encode_enum(_enum_status, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(encode_CommitStatus(r.status)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.status) != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.status = input.status; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PacketAcknowledgementCall library ReturnValue { //struct definition struct Data { bytes value; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_value(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.value = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.value.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.value = input.value; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ReturnValue
The decoder for internal usage p The offset of bytes array to start decode bs The bytes array to be decoded sz The number of bytes expected return The decoded struct return The number of bytes decoded/
function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_payload(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); }
13,056,724
//SPDX-License-Identifier: MIT pragma solidity ^0.8.7; 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; } 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); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); 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 feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface ERC20 { function decimals() external view returns(uint); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface ERC20RewardToken is ERC20 { function mint_rewards(uint256 qty, address receiver) external; function burn_tokens(uint256 qty, address burned) external; } contract protected { mapping(address => bool) is_auth; function is_it_auth(address addy) public view returns (bool) { return is_auth[addy]; } function set_is_auth(address addy, bool booly) public onlyAuth { is_auth[addy] = booly; } modifier onlyAuth() { require(is_auth[msg.sender] || msg.sender == owner, "not owner"); _; } address owner; modifier onlyOwner() { require(msg.sender == owner, "not owner"); _; } bool locked; modifier safe() { require(!locked, "reentrant"); locked = true; _; locked = false; } } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://eips.ethereum.org/EIPS/eip-721 /// Note: the ERC-165 identifier for this interface is 0x80ac58cd. interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) external payable; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } 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; } interface IUniswapRouter01 { 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 factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapRouter02 is IUniswapRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract smart { address router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address DEAD = 0x000000000000000000000000000000000000dEaD; IUniswapRouter02 router = IUniswapRouter02(router_address); uint kaiBalance; uint meishuBalance; uint kaiTax = 1; // 1% uint meishuFee = 100000000000000000; // 0,1 ETH function create_weth_pair(address token) private returns (address, IUniswapV2Pair) { address pair_address = IUniswapFactory(router.factory()).createPair(token, router.WETH()); return (pair_address, IUniswapV2Pair(pair_address)); } function get_weth_reserve(address pair_address) private view returns(uint, uint) { IUniswapV2Pair pair = IUniswapV2Pair(pair_address); uint112 token_reserve; uint112 native_reserve; uint32 last_timestamp; (token_reserve, native_reserve, last_timestamp) = pair.getReserves(); return (token_reserve, native_reserve); } function get_weth_price_impact(address token, uint amount, bool sell) private view returns(uint) { address pair_address = IUniswapFactory(router.factory()).getPair(token, router.WETH()); (uint res_token, uint res_weth) = get_weth_reserve(pair_address); uint impact; if(sell) { impact = (amount * 100) / res_token; } else { impact = (amount * 100) / res_weth; } return impact; } } contract calendar { function get_year_to_uint() public pure returns(uint) { return(365 days); } function get_month_to_uint() public pure returns(uint) { return(30 days); } function get_week_to_uint() public pure returns(uint) { return(7 days); } function get_day_to_uint() public pure returns(uint) { return(1 days); } function get_x_days_to_uint(uint16 _days) public pure returns(uint) { return((1 days*_days)); } } /******************** MEISHU NFT STAKING *********************/ contract MeishuStake is protected, smart,calendar { receive() payable external {} fallback() external {} mapping(address => bool) public nft_addresses; bool public nft_lock; address public default_earning; mapping(address => address) public custom_earning; mapping(address => mapping(uint => uint)) public nft_rewards; mapping(address => uint) public custom_floor; uint public _common_reward; ///@dev Modifiers rates uint burn_rate; uint penalty_rate; ///@dev Updated each time a floor is added or removed uint total_floors; struct SINGLE_STAKE { address nft; uint token_id; ERC721 nft_token; address earned; ERC20 earned_token; uint8 qty; uint floor; uint start_time; uint timelocked; uint rewards; bool active; bool exists; bool floor_based; } mapping(uint => bool) public times; struct STAKEHOLDER { mapping(uint => SINGLE_STAKE) stakes; uint total_withdraw; uint total_staked_value; uint last_stake; uint[] closed_pools; bool blacklisted; } mapping (address => STAKEHOLDER) stakeholder; constructor() { owner = msg.sender; is_auth[owner] = true; times[30 days] = true; times[60 days] = true; times[90 days] = true; /* 30 days = 2592000 60 days = 5184000 90 days = 7776000 */ } ///@dev Stake a specific NFT function stake_nft(address _nft, uint id, uint timelock) payable public safe { if(nft_lock) { require(nft_addresses[_nft], "This staking support other nfts"); } require(times[timelock], "Timelock wrong"); require(msg.value==meishuFee, "Underpaid or overpaid"); // 0.1 ETH pays for fees and gas uint kaiPart = (meishuFee * kaiTax)/100; kaiBalance += kaiPart; // 1% to Kaiba meishuBalance = meishuFee - kaiPart; require(ERC721(_nft).isApprovedForAll(msg.sender, address(this)), "Pleasea approve transfer status"); stakeholder[msg.sender].last_stake = stakeholder[msg.sender].last_stake + 1; uint last_stake = stakeholder[msg.sender].last_stake; // Configure the stake stakeholder[msg.sender].stakes[last_stake].nft = _nft; stakeholder[msg.sender].stakes[last_stake].nft_token = ERC721(_nft); // Check if there is a particular token to earn if(custom_earning[_nft]==DEAD) { stakeholder[msg.sender].stakes[last_stake].earned = default_earning; stakeholder[msg.sender].stakes[last_stake].earned_token = ERC20(default_earning); } else { stakeholder[msg.sender].stakes[last_stake].earned = custom_earning[_nft]; stakeholder[msg.sender].stakes[last_stake].earned_token = ERC20(custom_earning[_nft]); } // Check if there is a particular reward rate stakeholder[msg.sender].stakes[last_stake].rewards = _common_reward; // Transfer and last settings ERC721(_nft).transferFrom(msg.sender, address(this), id); stakeholder[msg.sender].stakes[last_stake].token_id = id; stakeholder[msg.sender].stakes[last_stake].qty = 1; stakeholder[msg.sender].stakes[last_stake].floor = custom_floor[_nft]; stakeholder[msg.sender].stakes[last_stake].start_time = block.timestamp; stakeholder[msg.sender].stakes[last_stake].active = true; stakeholder[msg.sender].stakes[last_stake].exists = true; total_floors += custom_floor[_nft]; } ///@dev Approve the transfer of a token (must be called before staking) function approve_nft_on_contract(address _nft) public { ERC721(_nft).setApprovalForAll(address(this), true); } ///@dev Set the burn rate function set_burn_rate(uint rate) public onlyAuth { burn_rate = rate; } ///@dev Set the penalty rate function set_penalty_rate(uint rate) public onlyAuth { penalty_rate = rate; } ///@dev Set the default earning token function set_base_earning(address _earning) public onlyAuth { default_earning = _earning; } ///@dev Set custom reward for an nft (yearly based) function set_nft_reward(address _nft, uint _time, uint _reward) public onlyAuth { nft_rewards[_nft][_time] = _reward; } function set_common_reward(uint _reward) public onlyAuth { _common_reward = _reward; } ///@dev Set custom earning token for an nft function set_custom_earning(address _nft, address _earning) public onlyAuth { custom_earning[_nft] = _earning; } ///@dev set floor for a specific nft function set_floor_on(address _nft, uint _floor) public onlyAuth { custom_floor[_nft] = _floor; } ///@dev set floor for a specific pool updating total_floors function set_pool_floor(address _stakeholder, uint _id, uint _floor) public onlyAuth { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); uint old_floor = stakeholder[_stakeholder].stakes[_id].floor; total_floors -= old_floor; stakeholder[_stakeholder].stakes[_id].floor = _floor; total_floors += _floor; } ///@dev invalidate a pool function invalidate_pool(address _stakeholder, uint _id) public onlyAuth { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); stakeholder[_stakeholder].stakes[_id].exists = false; uint old_floor = stakeholder[_stakeholder].stakes[_id].floor; total_floors -= old_floor; } ///@dev Enable or disable a time function set_time_status(uint timed, bool booly) public onlyAuth { times[timed] = booly; } ///@dev get balance function set_staking_fee(uint wei_fee) public onlyAuth { meishuFee = wei_fee; } ///@dev get balance function set_kaiba_share(uint perc_share) public onlyAuth { kaiTax = perc_share; } ///@dev get balance function retrieve_meishu_balance() public onlyAuth { if(!(address(this).balance >= meishuBalance)) { meishuBalance = (address(this).balance*kaiTax)/100; kaiBalance = address(this).balance - meishuBalance; } (bool sent,) = msg.sender.call{value: meishuBalance}(""); require(sent, "Can't withdraw"); } ///@dev get kaiba share function retrieve_kaiba_balance() public onlyAuth { if(!(address(this).balance >= kaiBalance)) { meishuBalance = (address(this).balance*kaiTax)/100; kaiBalance = address(this).balance - meishuBalance; } (bool sent,) = msg.sender.call{value: kaiBalance}(""); require(sent, "Can't withdraw"); } ///@dev solve stuck problems function unstuck() public onlyAuth { meishuBalance = 0; kaiBalance = 0; (bool sent,) = msg.sender.call{value: address(this).balance-1}(""); require(sent, "Can't withdraw"); } /************************* Views *************************/ ///@dev get a single pool function get_stakeholder_single_pool(address _stakeholder, uint _id) public view returns( address _nft, uint _nft_id, address _earned, uint _start_time, uint _locktime, uint _reward) { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); return( stakeholder[_stakeholder].stakes[_id].nft, stakeholder[_stakeholder].stakes[_id].token_id, stakeholder[_stakeholder].stakes[_id].earned, stakeholder[_stakeholder].stakes[_id].start_time, stakeholder[_stakeholder].stakes[_id].timelocked, stakeholder[_stakeholder].stakes[_id].rewards ); } ///@dev get all the pools function get_all_pools(address stkholder) public view returns (uint all_pools, uint[] memory closed_pools) { return( stakeholder[stkholder].last_stake, stakeholder[stkholder].closed_pools); } ///@dev calculate reward based on emission function get_rewards_on(address _stakeholder, uint _id) public view returns(uint _reward) { require(stakeholder[_stakeholder].stakes[_id].exists, "Pool is unconfigured"); require(stakeholder[_stakeholder].stakes[_id].active, "Pool is inactive"); uint reward = _common_reward; uint start_time = stakeholder[_stakeholder].stakes[_id].start_time; uint this_reward = _get_rewards(reward, start_time); return this_reward; } function _get_rewards(uint reward, uint start_time) private view returns (uint uf_reward){ uint delta_time = block.timestamp - start_time; uint year_perc = (delta_time * 1000000) / get_year_to_uint(); uint actual_reward = ((reward * year_perc) / 100)/10000; return actual_reward; } ///@dev Calculate annual return function get_annual_return(address _stakeholder, uint _id) public view returns (uint _reward_value){ address reward = stakeholder[_stakeholder].stakes[_id].earned; uint amount = get_rewards_on(_stakeholder, _id); uint reward_value = getTokenPrice(reward, amount); return reward_value; } ///@dev Calculate APY /* function get_apy(address _stakeholder, uint _id) public view returns (uint _apy){ address _nft = stakeholder[_stakeholder].stakes[_id].nft; address earned; uint reward; if(custom_earning[_nft]==DEAD) { earned = default_earning; } else { earned = custom_earning[_nft]; } // Check if there is a particular reward rate if(custom_reward[_nft]==0) { reward = default_reward; } else { reward = custom_reward[_nft]; } uint reward_value = getTokenPrice(earned, reward); uint apy = (reward_value*100)/reward; return apy; } */ ///@dev Tokens (ERC20) price function getTokenPrice(address tkn, uint amount) public view returns(uint) { IUniswapFactory factory = IUniswapFactory(router.factory()); address pairAddress = factory.getPair(tkn, router.WETH()); IUniswapV2Pair pair = IUniswapV2Pair(pairAddress); ERC20 token1 = ERC20(pair.token1()); (uint Res0, uint Res1,) = pair.getReserves(); // decimals uint res0 = Res0*(10**token1.decimals()); return((amount*res0)/Res1); // return amount of token0 needed to buy token1 } ///@dev Payout earnings function withdraw_earnings(address _stakeholder, uint _id) public safe { require(msg.sender == _stakeholder, "Don't steal"); require(block.timestamp >= (stakeholder[_stakeholder].stakes[_id].start_time+1 hours),"Wait."); bool penalty; if(block.timestamp < (stakeholder[_stakeholder].stakes[_id].start_time + 15 days)) { penalty = true; } address earning = stakeholder[_stakeholder].stakes[_id].earned; uint reward_amount_raw = get_rewards_on(_stakeholder, _id); uint burn_amount = (reward_amount_raw * burn_rate)/100; uint penalty_amount; if(penalty) { penalty_amount = (reward_amount_raw * penalty_rate)/100; } uint reward_amount = reward_amount_raw - burn_amount - penalty_amount; require(ERC20(earning).balanceOf(address(this)) >= reward_amount, "Not enough tokens"); ERC20(earning).transfer(_stakeholder, reward_amount); ERC20(earning).transfer(DEAD, burn_amount); stakeholder[_stakeholder].total_withdraw += reward_amount; stakeholder[_stakeholder].stakes[_id].start_time = block.timestamp; private_recover_pool(_stakeholder, _id, msg.sender, stakeholder[_stakeholder].stakes[_id].token_id); } /************************* Control Panel *************************/ function ctrl_disband() public onlyAuth { selfdestruct(payable(owner)); } function ctrl_allow_nft(address nftaddy, bool booly) public onlyAuth { nft_addresses[nftaddy] = booly; } function ctrl_universal_staking(bool booly) public onlyAuth { nft_lock = booly; } /// @dev Forcibly unset a pool function ctrl_unstuck_token(address _stakeholder, uint _id, address caller, uint _token_id) public onlyAuth { private_recover_pool(_stakeholder, _id, caller, _token_id); } /// @dev Forcibly set a pool function ctrl_remake_pool(address _nft, uint id, address staker) public onlyAuth { require(ERC721(_nft).isApprovedForAll(msg.sender, address(this)), "Pleasea approve transfer status"); stakeholder[staker].last_stake = stakeholder[staker].last_stake + 1; uint last_stake = stakeholder[staker].last_stake; // Configure the stake stakeholder[staker].stakes[last_stake].nft = _nft; stakeholder[staker].stakes[last_stake].nft_token = ERC721(_nft); // Check if there is a particular token to earn if(custom_earning[_nft]==DEAD) { stakeholder[staker].stakes[last_stake].earned = default_earning; stakeholder[staker].stakes[last_stake].earned_token = ERC20(default_earning); } else { stakeholder[staker].stakes[last_stake].earned = custom_earning[_nft]; stakeholder[staker].stakes[last_stake].earned_token = ERC20(custom_earning[_nft]); } // Check if there is a particular reward rate stakeholder[staker].stakes[last_stake].rewards = _common_reward; // Transfer and last settings ERC721(_nft).transferFrom(msg.sender, address(this), id); stakeholder[staker].stakes[last_stake].token_id = id; stakeholder[staker].stakes[last_stake].qty = 1; stakeholder[staker].stakes[last_stake].floor = custom_floor[_nft]; stakeholder[staker].stakes[last_stake].start_time = block.timestamp; stakeholder[staker].stakes[last_stake].active = true; stakeholder[staker].stakes[last_stake].exists = true; total_floors += custom_floor[_nft]; } /************************* Private Helpers *************************/ function private_recover_pool(address _stakeholder, uint _id, address caller, uint _token_id) private { // Update total floor uint old_floor = stakeholder[_stakeholder].stakes[_id].floor; total_floors -= old_floor; // Takes back nft if(!is_auth[caller]) { require(ERC721(stakeholder[_stakeholder].stakes[_id].nft).ownerOf(_token_id) == address(this), "Nope"); } ERC721(stakeholder[_stakeholder].stakes[_id].nft).transferFrom(address(this), caller, _token_id); // Unsetting all stakeholder[_stakeholder].closed_pools.push(_id); stakeholder[_stakeholder].stakes[_id].nft = DEAD; stakeholder[_stakeholder].stakes[_id].earned = DEAD; stakeholder[_stakeholder].stakes[_id].qty = 0; stakeholder[_stakeholder].stakes[_id].floor = 0; stakeholder[_stakeholder].stakes[_id].start_time = 0; stakeholder[_stakeholder].stakes[_id].rewards = 0; stakeholder[_stakeholder].stakes[_id].active = false; stakeholder[_stakeholder].stakes[_id].exists = false; stakeholder[_stakeholder].stakes[_id].floor_based = false; } }
Set the burn rate
function set_burn_rate(uint rate) public onlyAuth { burn_rate = rate; }
5,929,332
./full_match/3/0x4C0e952695C722FcF5fbf73326e3c7b91E58D46e/sources/browser/tbc_prac4.sol
SENDER_ACCOUNT => BALANCE - QTY RECEIVER_ACCOUNT => BALANCE + QTY
function AdminTokenTransfer(address payable sender, address payable receiver, uint qty) public { require(msg.sender == owner || msg.sender == creator, "The address that called this function can not administrate tokens tranferences"); require(balance[sender] >= qty, "Sender account has not enough tokens to transfer"); uint oldBalance = balance[sender]; balance[sender] = oldBalance - qty; balance[receiver] = balance[receiver] + qty; }
8,150,635
/** *Submitted for verification at Etherscan.io on 2021-08-11 */ /* ___ _ ___ _ | .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___ | _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._> |_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___. * PeriFinance: SupplySchedule.sol * * Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/SupplySchedule.sol * Docs: Will be added in the future. * https://docs.peri.finance/contracts/source/contracts/SupplySchedule * * Contract Dependencies: * - ISupplySchedule * - Owned * Libraries: * - Math * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 PeriFinance * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.5.16; // https://docs.peri.finance/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.peri.finance/contracts/source/interfaces/isupplyschedule interface ISupplySchedule { // Views function mintableSupply() external view returns (uint); function isMintable() external view returns (bool); function minterReward() external view returns (uint); // Mutative functions function recordMintEvent(uint supplyMinted) external returns (bool); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.peri.finance/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @dev Round down the value with given number */ function roundDownDecimal(uint x, uint d) internal pure returns (uint) { return x.div(10**d).mul(10**d); } /** * @dev Round up the value with given number */ function roundUpDecimal(uint x, uint d) internal pure returns (uint) { uint _decimal = 10**d; if (x % _decimal > 0) { x = x.add(10**d); } return x.div(_decimal).mul(_decimal); } } // Libraries // https://docs.peri.finance/contracts/source/libraries/math library Math { using SafeMath for uint; using SafeDecimalMath for uint; /** * @dev Uses "exponentiation by squaring" algorithm where cost is 0(logN) * vs 0(N) for naive repeated multiplication. * Calculates x^n with x as fixed-point and n as regular unsigned int. * Calculates to 18 digits of precision with SafeDecimalMath.unit() */ function powDecimal(uint x, uint n) internal pure returns (uint) { // https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/ uint result = SafeDecimalMath.unit(); while (n > 0) { if (n % 2 != 0) { result = result.multiplyDecimal(x); } x = x.multiplyDecimal(x); n /= 2; } return result; } } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // https://docs.peri.finance/contracts/source/interfaces/ipynth interface IPynth { // Views function currencyKey() external view returns (bytes32); function transferablePynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to PeriFinance function burn(address account, uint amount) external; function issue(address account, uint amount) external; } interface IVirtualPynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function pynth() external view returns (IPynth); // Mutative functions function settle(address account) external; } // https://docs.peri.finance/contracts/source/interfaces/iperiFinance interface IPeriFinance { // Views function getRequiredAddress(bytes32 contractName) external view returns (address); function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function externalTokenQuota( address _account, uint _additionalpUSD, uint _additionalExToken, bool _isIssue ) external view returns (uint); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey) external view returns (uint issueAmountToQuota, uint stakeAmountToQuota); function pynths(bytes32 currencyKey) external view returns (IPynth); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey) external view returns (uint); function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferablePeriFinance(address account) external view returns (uint transferable); // Mutative Functions function issuePynths(bytes32 _currencyKey, uint _issueAmount) external; function issueMaxPynths() external; function issuePynthsToMaxQuota(bytes32 _currencyKey) external; function burnPynths(bytes32 _currencyKey, uint _burnAmount) external; function fitToClaimable() external; function exit() external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualPynth vPynth); function mint(address _user, uint _amount) external returns (bool); function inflationalMint(uint _networkDebtShare) external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // Inheritance // Libraries // Internal references // https://docs.peri.finance/contracts/source/contracts/supplyschedule contract SupplySchedule is Owned, ISupplySchedule { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; uint public minterReward = 0; uint public constant INITIAL_WEEKLY_SUPPLY = 76924719527063029689120; // Address of the PeriFinanceProxy for the onlyPeriFinance modifier address payable public periFinanceProxy; // Max PERI rewards for minter uint public constant MAX_MINTER_REWARD = 200 ether; // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1625875200; // Saturday, July 10, 2021 9:00:00 AM GMT+09:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 52; uint8 public constant SUPPLY_DECAY_END = 172; // 40 months // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 50000000000000000; // 5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek ) public Owned(_owner) { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of PERI mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; if (currentWeek < SUPPLY_DECAY_START) { // If current week is before supply decay we add initial supply to mintableSupply totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } else if (currentWeek <= SUPPLY_DECAY_END) { // if current week before supply decay ends we add the new supply for the week // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START - 1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } else { // Terminal supply is calculated on the total supply of PeriFinance including any new supply // We can compound the remaining week's supply at the fixed terminal rate uint totalSupply = IERC20(periFinanceProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from PeriFinance by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of PERI the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlyPeriFinance returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of PERI for the caller of the public * function PeriFinance.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of PERI to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the PeriFinanceProxy should it ever change. * SupplySchedule requires PeriFinance address as it has the authority * to record mint event. * */ function setPeriFinanceProxy(IPeriFinance _periFinanceProxy) external onlyOwner { require(address(_periFinanceProxy) != address(0), "Address cannot be 0"); periFinanceProxy = address(uint160(address(_periFinanceProxy))); emit PeriFinanceProxyUpdated(periFinanceProxy); } // ========== MODIFIERS ========== /** * @notice Only the PeriFinance contract is authorised to call this function * */ modifier onlyPeriFinance() { require( msg.sender == address(Proxy(address(periFinanceProxy)).target()), "Only the periFinance contract can perform this action" ); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the PERI minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setPeriFinanceProxy is called changing the PeriFinance Proxy address * */ event PeriFinanceProxyUpdated(address newAddress); }
Record the mint event from PeriFinance by incrementing the inflation week counter for the number of weeks minted (probabaly always 1) and store the time of the event. supplyMinted the amount of PERI the total supply was inflated by. / add number of weeks minted to weekCounter Update mint event to latest week issued (start date + number of weeks issued seconds in week) 1 day time buffer is added so inflation is minted after feePeriod closes
function recordMintEvent(uint supplyMinted) external onlyPeriFinance returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); weekCounter = weekCounter.add(numberOfWeeksIssued); lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; }
2,455,337
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol"; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CertChain ERC721 token standard implementation * @author rjkz808 */ contract CertToken is ERC721 { using AddressUtils for address; using SafeMath for uint256; string internal constant name_ = "CertChain"; string internal constant symbol_ = "CRT"; uint8 internal constant decimals_ = 0; bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; uint256[] internal allTokens; mapping (uint256 => address) internal tokenOwner; mapping (uint256 => address) internal tokenApproval; mapping (address => mapping (address => bool)) internal operatorApproval; mapping (address => uint256[]) internal ownedTokens; mapping (uint256 => uint256) internal ownedTokensIndex; mapping (uint256 => uint256) internal allTokensIndex; mapping (uint256 => string) internal tokenURIs; mapping (bytes4 => bool) internal supportedInterfaces; event Burn(address indexed owner, uint256 tokenId); /** * @dev Reverts, if the `msg.sender` doesn't own the specified token * @param _tokenId uint256 ID of the token */ modifier onlyOwnerOf(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId)); _; } /** * @dev Constructor to register the implemented interfaces IDs */ constructor() public { _registerInterface(InterfaceId_ERC165); _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token short code * @return string the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Gets the token decimals * @notice This function is needed to keep the balance * @notice displayed in the MetaMask * @return uint8 the token decimals (0) */ function decimals() external pure returns (uint8) { return decimals_; } /** * @dev Gets the total issued tokens amount * @return uint256 the total tokens supply */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the balance of an account * @param _owner address the tokens holder * @return uint256 the account owned tokens amount */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokens[_owner].length; } /** * @dev Gets the specified token owner * @param _tokenId uint256 ID of the token * @return address the token owner */ function ownerOf(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenOwner[_tokenId]; } /** * @dev Gets the token existence state * @param _tokenId uint256 ID of the token * @return bool the token existence state */ function exists(uint256 _tokenId) public view returns (bool) { return tokenOwner[_tokenId] != address(0); } /** * @dev Gets the token approval * @param _tokenId uint256 ID of the token * @return address the token spender */ function getApproved(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenApproval[_tokenId]; } /** * @dev Gets the operator approval state * @param _owner address the tokens holder * @param _operator address the tokens spender * @return bool the operator approval state */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { require(_owner != address(0)); require(_operator != address(0)); return operatorApproval[_owner][_operator]; } /** * @dev Gets the specified address token ownership/spending state * @param _spender address the token spender * @param _tokenId uint256 the spending token ID * @return bool the ownership/spending state */ function isApprovedOrOwner(address _spender, uint256 _tokenId) public view returns (bool) { require(_spender != address(0)); require(exists(_tokenId)); return( _spender == ownerOf(_tokenId) || _spender == getApproved(_tokenId) || isApprovedForAll(ownerOf(_tokenId), _spender) ); } /** * @dev Gets the token ID by the ownedTokens list index * @param _owner address the token owner * @param _index uint256 the token index * @return uint256 the token ID */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_owner != address(0)); require(_index < ownedTokens[_owner].length); return ownedTokens[_owner][_index]; } /** * @dev Gets the token ID by the allTokens list index * @param _index uint256 the token index * @return uint256 the token ID */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < allTokens.length); return allTokens[_index]; } /** * @dev Gets the token URI * @param _tokenId uint256 ID of the token * @return string the token URI */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the interface support state * @param _interfaceId bytes4 ID of the interface * @return bool the specified interface support state */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { require(_interfaceId != 0xffffffff); return supportedInterfaces[_interfaceId]; } /** * @dev Function to approve token to spend it * @param _to address the token spender * @param _tokenId ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { require(msg.sender == ownerOf(_tokenId)); require(_to != address(0)); tokenApproval[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Function to set the operator approval for the all owned tokens * @param _operator address the tokens spender * @param _approved bool the tokens approval state */ function setApprovalForAll(address _operator, bool _approved) public { require(_operator != address(0)); operatorApproval[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Function to clear an approval of the owned token * @param _tokenId uint256 ID of the token */ function clearApproval(uint256 _tokenId) public onlyOwnerOf(_tokenId) { require(exists(_tokenId)); if (tokenApproval[_tokenId] != address(0)) { tokenApproval[_tokenId] = address(0); emit Approval(msg.sender, address(0), _tokenId); } } /** * @dev Function to send the owned/approved token * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_to != address(0)); _clearApproval(_tokenId); _removeTokenFrom(_from, _tokenId); _addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Function to send the owned/approved token with the * @dev onERC721Received function call if the token recepient is the * @dev smart contract * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Function to send the owned/approved token with the * @dev onERC721Received function call if the token recepient is the * @dev smart contract and with the additional transaction metadata * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes the transaction metadata */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); require(_onERC721Received(msg.sender, _from, _to, _tokenId, _data)); } /** * @dev Function to burn the owned token * @param _tokenId uint256 ID of the token to be burned */ function burn(uint256 _tokenId) public onlyOwnerOf(_tokenId) { _burn(msg.sender, _tokenId); } /** * @dev Function to burn the owned/approved token * @param _from address the token owner * @param _tokenId uint256 ID of the token to be burned */ function burnFrom(address _from, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); _burn(_from, _tokenId); } /** * @dev Internal function to clear an approval of the token * @param _tokenId uint256 ID of the token */ function _clearApproval(uint256 _tokenId) internal { require(exists(_tokenId)); if (tokenApproval[_tokenId] != address(0)) tokenApproval[_tokenId] = address(0); } /** * @dev Internal function to add the token to the account * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be added */ function _addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); require(_to != address(0)); tokenOwner[_tokenId] = _to; ownedTokensIndex[_tokenId] = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); } /** * @dev Internal function to remove the token from its owner address * @param _from address the token owner * @param _tokenId uint256 ID of the token */ function _removeTokenFrom(address _from, uint256 _tokenId) internal { require(_from == ownerOf(_tokenId)); uint256 lastToken = ownedTokens[_from][ownedTokens[_from].length.sub(1)]; ownedTokens[_from][ownedTokensIndex[_tokenId]] = lastToken; ownedTokens[_from][ownedTokensIndex[lastToken]] = 0; ownedTokens[_from].length = ownedTokens[_from].length.sub(1); ownedTokensIndex[lastToken] = ownedTokensIndex[_tokenId]; ownedTokensIndex[_tokenId] = 0; tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to call the `onERC721Received` function if the * @dev token recepient is the smart contract * @param _operator address the `transfer` function caller * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes the transaction metadata */ function _onERC721Received( address _operator, address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (_to.isContract()) { ERC721Receiver receiver = ERC721Receiver(_to); return ERC721_RECEIVED == receiver.onERC721Received( _operator, _from, _tokenId, _data ); } return true; } /** * @dev Internal function the token * @param _owner address the token owner * @param _tokenId ID of the token to be burned */ function _burn(address _owner, uint256 _tokenId) internal { if (bytes(tokenURIs[_tokenId]).length > 0) delete tokenURIs[_tokenId]; _clearApproval(_tokenId); _removeTokenFrom(_owner, _tokenId); uint256 lastToken = allTokens[allTokens.length.sub(1)]; allTokens[allTokensIndex[_tokenId]] = lastToken; allTokens[allTokensIndex[lastToken]] = 0; allTokens.length = allTokens.length.sub(1); allTokensIndex[lastToken] = allTokensIndex[_tokenId]; allTokensIndex[_tokenId] = 0; emit Transfer(_owner, address(0), _tokenId); emit Burn(_owner, _tokenId); } /** * @dev Internal function to issue new token * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be issued * @param _uri string the new token URI */ function _mint(address _to, uint256 _tokenId, string _uri) internal { require(_to != address(0)); _addTokenTo(_to, _tokenId); _setTokenURI(_tokenId, _uri); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to set the token URI * @param _tokenId ID of the token * @param _uri string the token URI */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to register the implemented interface * @param _interfaceId bytes4 ID of the interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } }
Gets the specified token owner _tokenId uint256 ID of the token return address the token owner/
function ownerOf(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenOwner[_tokenId]; }
6,435,003
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./HoldefiPausableOwnable.sol"; import "./HoldefiCollaterals.sol"; /// @notice File: contracts/HoldefiPrices.sol interface HoldefiPricesInterface { function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value); function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount); } /// @notice File: contracts/HoldefiSettings.sol interface HoldefiSettingsInterface { /// @notice Markets Features struct MarketSettings { bool isExist; bool isActive; uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; bool isActive; uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } function getInterests(address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate); function resetPromotionRate (address market) external; function getMarketsList() external view returns(address[] memory marketsList); function marketAssets(address market) external view returns(MarketSettings memory); function collateralAssets(address collateral) external view returns(CollateralSettings memory); } /// @title Main Holdefi contract /// @author Holdefi Team /// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE /// @dev All indexes are scaled by (secondsPerYear * rateDecimals) /// @dev All values are based ETH price considered 1 and all values decimals considered 30 contract Holdefi is HoldefiPausableOwnable { using SafeMath for uint256; /// @notice Markets are assets can be supplied and borrowed struct Market { uint256 totalSupply; uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals uint256 supplyIndexUpdateTime; uint256 totalBorrow; uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals uint256 borrowIndexUpdateTime; uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionReserveLastUpdateTime; uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionDebtLastUpdateTime; } /// @notice Collaterals are assets can be used only as collateral for borrowing with no interest struct Collateral { uint256 totalCollateral; uint256 totalLiquidatedCollateral; } /// @notice Users profile for each market struct MarketAccount { mapping (address => uint) allowance; uint256 balance; uint256 accumulatedInterest; uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals } /// @notice Users profile for each collateral struct CollateralAccount { mapping (address => uint) allowance; uint256 balance; uint256 lastUpdateTime; } struct MarketData { uint256 balance; uint256 interest; uint256 currentIndex; } address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice All rates in this contract are scaled by rateDecimals uint256 constant public rateDecimals = 10 ** 4; uint256 constant public secondsPerYear = 31536000; /// @dev For round up borrow interests uint256 constant private oneUnit = 1; /// @dev Used for calculating liquidation threshold /// @dev There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; /// @notice Contract for getting protocol settings HoldefiSettingsInterface public holdefiSettings; /// @notice Contract for getting asset prices HoldefiPricesInterface public holdefiPrices; /// @notice Contract for holding collaterals HoldefiCollaterals public holdefiCollaterals; /// @dev Markets: marketAddress => marketDetails mapping (address => Market) public marketAssets; /// @dev Collaterals: collateralAddress => collateralDetails mapping (address => Collateral) public collateralAssets; /// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance mapping (address => mapping (address => uint)) public marketDebt; /// @dev Users Supplies: userAddress => marketAddress => supplyDetails mapping (address => mapping (address => MarketAccount)) private supplies; /// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows; /// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails mapping (address => mapping (address => CollateralAccount)) private collaterals; // ----------- Events ----------- /// @notice Event emitted when a market asset is supplied event Supply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a supply is withdrawn event WithdrawSupply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when a collateral asset is deposited event Collateralize( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a collateral is withdrawn event WithdrawCollateral( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a market asset is borrowed event Borrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a borrow is repaid event RepayBorrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when the supply index is updated for a market asset event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate); /// @notice Event emitted when the borrow index is updated for a market asset event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex); /// @notice Event emitted when a collateral is liquidated event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral ); /// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market event BuyLiquidatedCollateral( address indexed market, address indexed collateral, uint256 marketAmount, uint256 collateralAmount ); /// @notice Event emitted when HoldefiPrices contract is changed event HoldefiPricesContractChanged(address newAddress, address oldAddress); /// @notice Event emitted when a liquidation reserve is withdrawn by the owner event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount); /// @notice Event emitted when a liquidation reserve is deposited event LiquidationReserveDeposited(address indexed collateral, uint256 amount); /// @notice Event emitted when a promotion reserve is withdrawn by the owner event PromotionReserveWithdrawn(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is deposited event PromotionReserveDeposited(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is updated event PromotionReserveUpdated(address indexed market, uint256 promotionReserve); /// @notice Event emitted when a promotion debt is updated event PromotionDebtUpdated(address indexed market, uint256 promotionDebt); /// @notice Initializes the Holdefi contract /// @param holdefiSettingsAddress Holdefi settings contract address /// @param holdefiPricesAddress Holdefi prices contract address constructor( HoldefiSettingsInterface holdefiSettingsAddress, HoldefiPricesInterface holdefiPricesAddress ) public { holdefiSettings = holdefiSettingsAddress; holdefiPrices = holdefiPricesAddress; holdefiCollaterals = new HoldefiCollaterals(); } /// @dev Modifier to check if the asset is ETH or not /// @param asset Address of the given asset modifier isNotETHAddress(address asset) { require (asset != ethAddress, "Asset should not be ETH address"); _; } /// @dev Modifier to check if the market is active or not /// @param market Address of the given market modifier marketIsActive(address market) { require (holdefiSettings.marketAssets(market).isActive, "Market is not active"); _; } /// @dev Modifier to check if the collateral is active or not /// @param collateral Address of the given collateral modifier collateralIsActive(address collateral) { require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active"); _; } /// @dev Modifier to check if the account address is equal to the msg.sender or not /// @param account The given account address modifier accountIsValid(address account) { require (msg.sender != account, "Account is not valid"); _; } receive() external payable { revert(); } /// @notice Returns balance and interest of an account for a given market /// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex)) /// @param account Supplier address to get supply information /// @param market Address of the given market /// @return balance Supplied amount on the specified market /// @return interest Profit earned /// @return currentSupplyIndex Supply index for the given market at current time function getAccountSupply(address account, address market) public view returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex) { balance = supplies[account][market].balance; (currentSupplyIndex,,) = getCurrentSupplyIndex(market); uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); interest = supplies[account][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns balance and interest of an account for a given market on a given collateral /// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex)) /// @param account Borrower address to get Borrow information /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return balance Borrowed amount on the specified market /// @return interest The amount of interest the borrower should pay /// @return currentBorrowIndex Borrow index for the given market at current time function getAccountBorrow(address account, address market, address collateral) public view returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex) { balance = borrows[account][collateral][market].balance; (currentBorrowIndex,,) = getCurrentBorrowIndex(market); uint256 deltaInterestIndex = currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); if (balance > 0) { deltaInterest = deltaInterest.add(oneUnit); } interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral /// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue /// @dev liquidationThreshold = collateralValueToLoanRate - 5% /// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold /// @param account Account address to get collateral information /// @param collateral Address of the given collateral /// @return balance Amount of the specified collateral /// @return timeSinceLastActivity Time since last activity performed by the account /// @return borrowPowerValue The borrowing power for the account of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral /// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not function getAccountCollateral(address account, address collateral) public view returns ( uint256 balance, uint256 timeSinceLastActivity, uint256 borrowPowerValue, uint256 totalBorrowValue, bool underCollateral ) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; if (valueToLoanRate == 0) { return (0, 0, 0, 0, false); } balance = collaterals[account][collateral].balance; uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance); uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap); uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate); uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate); totalBorrowValue = getAccountTotalBorrowValue(account, collateral); if (totalBorrowValue > 0) { timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime); } borrowPowerValue = 0; if (totalBorrowValue < totalBorrowPowerValue) { borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue); } underCollateral = false; if (totalBorrowValue > liquidationThresholdValue) { underCollateral = true; } } /// @notice Returns maximum amount spender can withdraw from account supplies on a given market /// @param account Supplier address /// @param spender Spender address /// @param market Address of the given market /// @return res Maximum amount spender can withdraw from account supplies on a given market function getAccountWithdrawSupplyAllowance (address account, address spender, address market) external view returns (uint256 res) { res = supplies[account][market].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account balance on a given collateral /// @param account Account address /// @param spender Spender address /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account balance on a given collateral function getAccountWithdrawCollateralAllowance ( address account, address spender, address collateral ) external view returns (uint256 res) { res = collaterals[account][collateral].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral /// @param account Borrower address /// @param spender Spender address /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral function getAccountBorrowAllowance ( address account, address spender, address market, address collateral ) external view returns (uint256 res) { res = borrows[account][collateral][market].allowance[spender]; } /// @notice Returns total borrow value of an account based on a given collateral /// @param account Account address /// @param collateral Address of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral function getAccountTotalBorrowValue (address account, address collateral) public view returns (uint256 totalBorrowValue) { MarketData memory borrowData; address market; uint256 totalDebt; uint256 assetValue; totalBorrowValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; (borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral); totalDebt = borrowData.balance.add(borrowData.interest); assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt); totalBorrowValue = totalBorrowValue.add(assetValue); } } /// @notice The collateral reserve amount for buying liquidated collateral /// @param collateral Address of the given collateral /// @return reserve Liquidation reserves for the given collateral function getLiquidationReserve (address collateral) public view returns(uint256 reserve) { address market; uint256 assetValue; uint256 totalDebtValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]); totalDebtValue = totalDebtValue.add(assetValue); } uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals); uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue( collateral, totalDebtCollateralValue ); reserve = 0; uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; if (totalLiquidatedCollateral > liquidatedCollateralNeeded) { reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded); } } /// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param marketAmount The amount of market should be paid /// @return collateralAmountWithDiscount Amount of discounted collateral can be bought function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount) public view returns (uint256 collateralAmountWithDiscount) { uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount); uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals); collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue); } /// @notice Returns supply index and supply rate for a given market at current time /// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate) /// @param market Address of the given market /// @return supplyIndex Supply index of the given market /// @return supplyRate Supply rate of the given market /// @return currentTime Current block timestamp function getCurrentSupplyIndex (address market) public view returns ( uint256 supplyIndex, uint256 supplyRate, uint256 currentTime ) { (, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime); supplyRate = supplyRateBase.add(promotionRate); uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate); supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest); } /// @notice Returns borrow index and borrow rate for the given market at current time /// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate) /// @param market Address of the given market /// @return borrowIndex Borrow index of the given market /// @return borrowRate Borrow rate of the given market /// @return currentTime Current block timestamp function getCurrentBorrowIndex (address market) public view returns ( uint256 borrowIndex, uint256 borrowRate, uint256 currentTime ) { borrowRate = holdefiSettings.marketAssets(market).borrowRate; currentTime = block.timestamp; uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime); uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate); borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest); } /// @notice Returns promotion reserve for a given market at current time /// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals) /// @param market Address of the given market /// @return promotionReserveScaled Promotion reserve of the given market /// @return currentTime Current block timestamp function getPromotionReserve (address market) public view returns (uint256 promotionReserveScaled, uint256 currentTime) { (uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase); uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate); uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime); uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest); } /// @notice Returns promotion debt for a given market at current time /// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals /// @param market Address of the given market /// @return promotionDebtScaled Promotion debt of the given market /// @return currentTime Current block timestamp function getPromotionDebt (address market) public view returns (uint256 promotionDebtScaled, uint256 currentTime) { uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate; currentTime = block.timestamp; promotionDebtScaled = marketAssets[market].promotionDebtScaled; if (promotionRate != 0) { uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime); uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest); } } /// @notice Update a market supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeSupplyRate (address market) public { updateSupplyIndex(market); updatePromotionReserve(market); updatePromotionDebt(market); } /// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeBorrowRate (address market) external { updateBorrowIndex(market); beforeChangeSupplyRate(market); } /// @notice Deposit ERC20 asset for supplying /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(msg.sender, market, amount, referralCode); } /// @notice Deposit ETH for supplying /// @notice msg.value The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(uint16 referralCode) external payable { supplyInternal(msg.sender, ethAddress, msg.value, referralCode); } /// @notice Sender deposits ERC20 asset belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(account, market, amount, referralCode); } /// @notice Sender deposits ETH belonging to the supplier /// @notice msg.value The amount of ETH sender deposits belonging to the supplier /// @param account Address of the supplier /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, uint16 referralCode) external payable { supplyInternal(account, ethAddress, msg.value, referralCode); } /// @notice Sender approves of the withdarawl for the account in the market asset /// @param account Address of the account allowed to withdrawn /// @param market Address of the given market /// @param amount The amount is allowed to withdrawn function approveWithdrawSupply(address account, address market, uint256 amount) external accountIsValid(account) marketIsActive(market) { supplies[msg.sender][market].allowance[account] = amount; } /// @notice Withdraw supply of a given market /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupply(address market, uint256 amount) external { withdrawSupplyInternal(msg.sender, market, amount); } /// @notice Sender withdraws supply belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupplyBehalf(address account, address market, uint256 amount) external { uint256 allowance = supplies[account][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); supplies[account][market].allowance[msg.sender] = allowance.sub(amount); withdrawSupplyInternal(account, market, amount); } /// @notice Deposit ERC20 asset as a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralize (address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(msg.sender, collateral, amount); } /// @notice Deposit ETH as a collateral /// @notice msg.value The amount of ETH will be collateralized function collateralize () external payable { collateralizeInternal(msg.sender, ethAddress, msg.value); } /// @notice Sender deposits ERC20 asset as a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralizeBehalf (address account, address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(account, collateral, amount); } /// @notice Sender deposits ETH as a collateral belonging to the user /// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user /// @param account Address of the user function collateralizeBehalf (address account) external payable { collateralizeInternal(account, ethAddress, msg.value); } /// @notice Sender approves the account to withdraw the collateral /// @param account Address is allowed to withdraw the collateral /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveWithdrawCollateral (address account, address collateral, uint256 amount) external accountIsValid(account) collateralIsActive(collateral) { collaterals[msg.sender][collateral].allowance[account] = amount; } /// @notice Withdraw a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateral (address collateral, uint256 amount) external { withdrawCollateralInternal(msg.sender, collateral, amount); } /// @notice Sender withdraws a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateralBehalf (address account, address collateral, uint256 amount) external { uint256 allowance = collaterals[account][collateral].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount); withdrawCollateralInternal(account, collateral, amount); } /// @notice Sender approves the account to borrow a given market based on given collateral /// @param account Address that is allowed to borrow the given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveBorrow (address account, address market, address collateral, uint256 amount) external accountIsValid(account) marketIsActive(market) { borrows[msg.sender][collateral][market].allowance[account] = amount; } /// @notice Borrow an asset /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the given market will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrow (address market, address collateral, uint256 amount, uint16 referralCode) external { borrowInternal(msg.sender, market, collateral, amount, referralCode); } /// @notice Sender borrows an asset belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode) external { uint256 allowance = borrows[account][collateral][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount); borrowInternal(account, market, collateral, amount, referralCode); } /// @notice Repay an ERC20 asset based on a given collateral /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be Repaid function repayBorrow (address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(msg.sender, market, collateral, amount); } /// @notice Repay an ETH based on a given collateral /// @notice msg.value The amount of ETH will be repaid /// @param collateral Address of the given collateral function repayBorrow (address collateral) external payable { repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value); } /// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be repaid function repayBorrowBehalf (address account, address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(account, market, collateral, amount); } /// @notice Sender repays an ETH based on a given collateral belonging to the borrower /// @notice msg.value The amount of ETH sender repays belonging to the borrower /// @param account Address of the borrower /// @param collateral Address of the given collateral function repayBorrowBehalf (address account, address collateral) external payable { repayBorrowInternal(account, ethAddress, collateral, msg.value); } /// @notice Liquidate borrower's collateral /// @param borrower Address of the borrower who should be liquidated /// @param market Address of the given market /// @param collateral Address of the given collateral function liquidateBorrowerCollateral (address borrower, address market, address collateral) external whenNotPaused("liquidateBorrowerCollateral") { MarketData memory borrowData; (borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral); require(borrowData.balance > 0, "User should have debt"); (uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) = getAccountCollateral(borrower, collateral); require (underCollateral || (timeSinceLastActivity > secondsPerYear), "User should be under collateral or time is over" ); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance); uint256 liquidatedCollateralValue = totalBorrowedBalanceValue .mul(holdefiSettings.collateralAssets(collateral).penaltyRate) .div(rateDecimals); uint256 liquidatedCollateral = holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue); if (liquidatedCollateral > collateralBalance) { liquidatedCollateral = collateralBalance; } collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral); collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral); collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral); delete borrows[borrower][collateral][market]; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance); marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance); emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral); } /// @notice Buy collateral in exchange for ERC20 asset /// @param market Address of the market asset should be paid to buy collateral /// @param collateral Address of the liquidated collateral /// @param marketAmount The amount of the given market will be paid function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount) external isNotETHAddress(market) { buyLiquidatedCollateralInternal(market, collateral, marketAmount); } /// @notice Buy collateral in exchange for ETH /// @notice msg.value The amount of the given market that will be paid /// @param collateral Address of the liquidated collateral function buyLiquidatedCollateral (address collateral) external payable { buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value); } /// @notice Deposit ERC20 asset as liquidation reserve /// @param collateral Address of the given collateral /// @param amount The amount that will be deposited function depositLiquidationReserve(address collateral, uint256 amount) external isNotETHAddress(collateral) { depositLiquidationReserveInternal(collateral, amount); } /// @notice Deposit ETH asset as liquidation reserve /// @notice msg.value The amount of ETH that will be deposited function depositLiquidationReserve() external payable { depositLiquidationReserveInternal(ethAddress, msg.value); } /// @notice Withdraw liquidation reserve only by the owner /// @param collateral Address of the given collateral /// @param amount The amount that will be withdrawn function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner { uint256 maxWithdraw = getLiquidationReserve(collateral); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit LiquidationReserveWithdrawn(collateral, amount); } /// @notice Deposit ERC20 asset as promotion reserve /// @param market Address of the given market /// @param amount The amount that will be deposited function depositPromotionReserve (address market, uint256 amount) external isNotETHAddress(market) { depositPromotionReserveInternal(market, amount); } /// @notice Deposit ETH as promotion reserve /// @notice msg.value The amount of ETH that will be deposited function depositPromotionReserve () external payable { depositPromotionReserveInternal(ethAddress, msg.value); } /// @notice Withdraw promotion reserve only by the owner /// @param market Address of the given market /// @param amount The amount that will be withdrawn function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner { (uint256 reserveScaled,) = getPromotionReserve(market); (uint256 debtScaled,) = getPromotionDebt(market); uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); uint256 increasedDebtScaled = amountScaled.add(debtScaled); require (reserveScaled > increasedDebtScaled, "Amount should be less than max"); marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled); transferFromHoldefi(msg.sender, market, amount); emit PromotionReserveWithdrawn(market, amount); } /// @notice Set Holdefi prices contract only by the owner /// @param newHoldefiPrices Address of the new Holdefi prices contract function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner { emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices)); holdefiPrices = newHoldefiPrices; } /// @notice Promotion reserve and debt settlement /// @param market Address of the given market function reserveSettlement (address market) external { require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract"); uint256 promotionReserve = marketAssets[market].promotionReserveScaled; uint256 promotionDebt = marketAssets[market].promotionDebtScaled; require(promotionReserve > promotionDebt, "Not enough promotion reserve"); promotionReserve = promotionReserve.sub(promotionDebt); marketAssets[market].promotionReserveScaled = promotionReserve; marketAssets[market].promotionDebtScaled = 0; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, promotionReserve); emit PromotionDebtUpdated(market, 0); } /// @notice Update supply index of a market /// @param market Address of the given market function updateSupplyIndex (address market) internal { (uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) = getCurrentSupplyIndex(market); marketAssets[market].supplyIndex = currentSupplyIndex; marketAssets[market].supplyIndexUpdateTime = currentTime; emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate); } /// @notice Update borrow index of a market /// @param market Address of the given market function updateBorrowIndex (address market) internal { (uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market); marketAssets[market].borrowIndex = currentBorrowIndex; marketAssets[market].borrowIndexUpdateTime = currentTime; emit UpdateBorrowIndex(market, currentBorrowIndex); } /// @notice Update promotion reserve of a market /// @param market Address of the given market function updatePromotionReserve(address market) internal { (uint256 reserveScaled,) = getPromotionReserve(market); marketAssets[market].promotionReserveScaled = reserveScaled; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, reserveScaled); } /// @notice Update promotion debt of a market /// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve) /// @param market Address of the given market function updatePromotionDebt(address market) internal { (uint256 debtScaled,) = getPromotionDebt(market); if (marketAssets[market].promotionDebtScaled != debtScaled){ marketAssets[market].promotionDebtScaled = debtScaled; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionDebtUpdated(market, debtScaled); } if (marketAssets[market].promotionReserveScaled <= debtScaled) { holdefiSettings.resetPromotionRate(market); } } /// @notice transfer ETH or ERC20 asset from this contract function transferFromHoldefi(address receiver, address asset, uint256 amount) internal { bool success = false; if (asset == ethAddress){ (success, ) = receiver.call{value:amount}(""); } else { IERC20 token = IERC20(asset); success = token.transfer(receiver, amount); } require (success, "Cannot Transfer"); } /// @notice transfer ERC20 asset to this contract function transferToHoldefi(address receiver, address asset, uint256 amount) internal { IERC20 token = IERC20(asset); bool success = token.transferFrom(msg.sender, receiver, amount); require (success, "Cannot Transfer"); } /// @notice Perform supply operation function supplyInternal(address account, address market, uint256 amount, uint16 referralCode) internal whenNotPaused("supply") marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); supplyData.balance = supplyData.balance.add(amount); supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount); emit Supply( msg.sender, account, market, amount, supplyData.balance, supplyData.interest, supplyData.currentIndex, referralCode ); } /// @notice Perform withdraw supply operation function withdrawSupplyInternal (address account, address market, uint256 amount) internal whenNotPaused("withdrawSupply") { MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest); require (totalSuppliedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalSuppliedBalance){ transferAmount = totalSuppliedBalance; } uint256 remaining = 0; if (transferAmount <= supplyData.interest) { supplyData.interest = supplyData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(supplyData.interest); supplyData.interest = 0; supplyData.balance = supplyData.balance.sub(remaining); } supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining); transferFromHoldefi(msg.sender, market, transferAmount); emit WithdrawSupply( msg.sender, account, market, transferAmount, supplyData.balance, supplyData.interest, supplyData.currentIndex ); } /// @notice Perform collateralize operation function collateralizeInternal (address account, address collateral, uint256 amount) internal whenNotPaused("collateralize") collateralIsActive(collateral) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } uint256 balance = collaterals[account][collateral].balance.add(amount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount); emit Collateralize(msg.sender, account, collateral, amount, balance); } /// @notice Perform withdraw collateral operation function withdrawCollateralInternal (address account, address collateral, uint256 amount) internal whenNotPaused("withdrawCollateral") { (uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) = getAccountCollateral(account, collateral); require (borrowPowerValue != 0, "Borrow power should not be zero"); uint256 collateralNedeed = 0; if (totalBorrowValue != 0) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals); collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue); } uint256 maxWithdraw = balance.sub(collateralNedeed); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } balance = balance.sub(transferAmount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance); } /// @notice Perform borrow operation function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode) internal whenNotPaused("borrow") marketIsActive(market) collateralIsActive(collateral) { require ( amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)), "Amount should be less than cash" ); (,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral); uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount); require ( borrowPowerValue >= assetToBorrowValue, "Borrow power should be more than new borrow value" ); MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); borrowData.balance = borrowData.balance.add(amount); borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount); transferFromHoldefi(msg.sender, market, amount); emit Borrow( msg.sender, account, market, collateral, amount, borrowData.balance, borrowData.interest, borrowData.currentIndex, referralCode ); } /// @notice Perform repay borrow operation function repayBorrowInternal (address account, address market, address collateral, uint256 amount) internal whenNotPaused("repayBorrow") { MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); require (totalBorrowedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalBorrowedBalance) { transferAmount = totalBorrowedBalance; if (market == ethAddress) { uint256 extra = amount.sub(transferAmount); transferFromHoldefi(msg.sender, ethAddress, extra); } } if (market != ethAddress) { transferToHoldefi(address(this), market, transferAmount); } uint256 remaining = 0; if (transferAmount <= borrowData.interest) { borrowData.interest = borrowData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(borrowData.interest); borrowData.interest = 0; borrowData.balance = borrowData.balance.sub(remaining); } borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining); emit RepayBorrow ( msg.sender, account, market, collateral, transferAmount, borrowData.balance, borrowData.interest, borrowData.currentIndex ); } /// @notice Perform buy liquidated collateral operation function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount) internal whenNotPaused("buyLiquidatedCollateral") { uint256 debt = marketDebt[collateral][market]; require (marketAmount <= debt, "Amount should be less than total liquidated assets" ); uint256 collateralAmountWithDiscount = getDiscountedCollateralAmount(market, collateral, marketAmount); uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; require ( collateralAmountWithDiscount <= totalLiquidatedCollateral, "Collateral amount with discount should be less than total liquidated assets" ); if (market != ethAddress) { transferToHoldefi(address(this), market, marketAmount); } collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount); marketDebt[collateral][market] = debt.sub(marketAmount); holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount); emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount); } /// @notice Perform deposit promotion reserve operation function depositPromotionReserveInternal (address market, uint256 amount) internal marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); marketAssets[market].promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(amountScaled); emit PromotionReserveDeposited(market, amount); } /// @notice Perform deposit liquidation reserve operation function depositLiquidationReserveInternal (address collateral, uint256 amount) internal collateralIsActive(ethAddress) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } collateralAssets[ethAddress].totalLiquidatedCollateral = collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value); emit LiquidationReserveDeposited(ethAddress, msg.value); } }
Perform withdraw supply operation
function withdrawSupplyInternal (address account, address market, uint256 amount) internal whenNotPaused("withdrawSupply") { MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest); require (totalSuppliedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalSuppliedBalance){ transferAmount = totalSuppliedBalance; } uint256 remaining = 0; if (transferAmount <= supplyData.interest) { supplyData.interest = supplyData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(supplyData.interest); supplyData.interest = 0; supplyData.balance = supplyData.balance.sub(remaining); } supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining); transferFromHoldefi(msg.sender, market, transferAmount); emit WithdrawSupply( msg.sender, account, market, transferAmount, supplyData.balance, supplyData.interest, supplyData.currentIndex ); }
13,514,385
pragma solidity 0.5.17; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import {FeeRebateToken} from "./FeeRebateToken.sol"; import {TBTCToken} from "./TBTCToken.sol"; import {TBTCConstants} from "./TBTCConstants.sol"; import "../deposit/Deposit.sol"; import "./TBTCSystemAuthority.sol"; /// @title Vending Machine /// @notice The Vending Machine swaps TDTs (`TBTCDepositToken`) /// to TBTC (`TBTCToken`) and vice versa. /// @dev The Vending Machine should have exclusive TBTC and FRT (`FeeRebateToken`) minting /// privileges. contract VendingMachine is TBTCSystemAuthority{ using SafeMath for uint256; TBTCToken tbtcToken; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; uint256 createdAt; constructor(address _systemAddress) TBTCSystemAuthority(_systemAddress) public { createdAt = block.timestamp; } /// @notice Set external contracts needed by the Vending Machine. /// @dev Addresses are used to update the local contract instance. /// @param _tbtcToken TBTCToken contract. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT) contract. More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT) contract. More info in `FeeRebateToken`. function setExternalAddresses( TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken ) external onlyTbtcSystem { tbtcToken = _tbtcToken; tbtcDepositToken = _tbtcDepositToken; feeRebateToken = _feeRebateToken; } /// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller /// as long as it is qualified. /// @dev We burn the lotSize of the Deposit in order to maintain /// the TBTC supply peg in the Vending Machine. VendingMachine must be approved /// by the caller to burn the required amount. /// @param _tdtId ID of tBTC Deposit Token to buy. function tbtcToTdt(uint256 _tdtId) external { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc(); require(tbtcToken.balanceOf(msg.sender) >= depositValue, "Not enough TBTC for TDT exchange"); tbtcToken.burnFrom(msg.sender, depositValue); // TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case. require(tbtcDepositToken.ownerOf(_tdtId) == address(this), "Deposit is locked"); tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId); } /// @notice Transfer the tBTC Deposit Token and mint TBTC. /// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller. /// Vending Machine must be approved to transfer TDT by the caller. /// @param _tdtId ID of tBTC Deposit Token to sell. function tdtToTbtc(uint256 _tdtId) public { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId); Deposit deposit = Deposit(address(uint160(_tdtId))); uint256 signerFee = deposit.signerFeeTbtc(); uint256 depositValue = deposit.lotSizeTbtc(); require(canMint(depositValue), "Can't mint more than the max supply cap"); // If the backing Deposit does not have a signer fee in escrow, mint it. if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) { tbtcToken.mint(msg.sender, depositValue.sub(signerFee)); tbtcToken.mint(address(_tdtId), signerFee); } else{ tbtcToken.mint(msg.sender, depositValue); } // owner of the TDT during first TBTC mint receives the FRT if(!feeRebateToken.exists(_tdtId)){ feeRebateToken.mint(msg.sender, _tdtId); } } /// @notice Return whether an amount of TBTC can be minted according to the supply cap /// schedule /// @dev This function is also used by TBTCSystem to decide whether to allow a new deposit. /// @return True if the amount can be minted without hitting the max supply, false otherwise. function canMint(uint256 amount) public view returns (bool) { return getMintedSupply().add(amount) < getMaxSupply(); } /// @notice Determines whether a deposit is qualified for minting TBTC. /// @param _depositAddress The address of the deposit function isQualified(address payable _depositAddress) public view returns (bool) { return Deposit(_depositAddress).inActive(); } /// @notice Return the minted TBTC supply in weitoshis (BTC * 10 ** 18). function getMintedSupply() public view returns (uint256) { return tbtcToken.totalSupply(); } /// @notice Get the maximum TBTC token supply based on the age of the /// contract deployment. The supply cap starts at 2 BTC for the two /// days, 100 for the first week, 250 for the next, then 500, 750, /// 1000, 1500, 2000, 2500, and 3000... finally removing the minting /// restriction after 9 weeks and returning 21M BTC as a sanity /// check. /// @return The max supply in weitoshis (BTC * 10 ** 18). function getMaxSupply() public view returns (uint256) { uint256 age = block.timestamp - createdAt; if(age < 2 days) { return 2 * 10 ** 18; } if (age < 7 days) { return 100 * 10 ** 18; } if (age < 14 days) { return 250 * 10 ** 18; } if (age < 21 days) { return 500 * 10 ** 18; } if (age < 28 days) { return 750 * 10 ** 18; } if (age < 35 days) { return 1000 * 10 ** 18; } if (age < 42 days) { return 1500 * 10 ** 18; } if (age < 49 days) { return 2000 * 10 ** 18; } if (age < 56 days) { return 2500 * 10 ** 18; } if (age < 63 days) { return 3000 * 10 ** 18; } return 21e6 * 10 ** 18; } // WRAPPERS /// @notice Qualifies a deposit and mints TBTC. /// @dev User must allow VendingManchine to transfer TDT. function unqualifiedDepositToTbtc( address payable _depositAddress, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters Deposit _d = Deposit(_depositAddress); _d.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); tdtToTbtc(uint256(_depositAddress)); } /// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient, /// and using the TDT to redeem corresponding Deposit as _finalRecipient. /// This function will revert if the Deposit is not in ACTIVE state. /// @dev Vending Machine transfers TBTC allowance to Deposit. /// @param _depositAddress The address of the Deposit to redeem. /// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function tbtcToBtc( address payable _depositAddress, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist"); Deposit _d = Deposit(_depositAddress); tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc()); tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress)); uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender); if(tbtcOwed != 0){ tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed); tbtcToken.approve(_depositAddress, tbtcOwed); } _d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, msg.sender); } } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity 0.5.17; /** * @title Keep interface */ interface ITBTCSystem { // expected behavior: // return the price of 1 sat in wei // these are the native units of the deposit contract function fetchBitcoinPrice() external view returns (uint256); // passthrough requests for the oracle function fetchRelayCurrentDifficulty() external view returns (uint256); function fetchRelayPreviousDifficulty() external view returns (uint256); function getNewDepositFeeEstimate() external view returns (uint256); function getAllowNewDeposits() external view returns (bool); function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) external view returns (bool); function requestNewKeep(uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime) external payable returns (address); function getSignerFeeDivisor() external view returns (uint16); function getInitialCollateralizedPercent() external view returns (uint16); function getUndercollateralizedThresholdPercent() external view returns (uint16); function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16); } pragma solidity 0.5.17; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import "../system/DepositFactoryAuthority.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. /// @title tBTC Deposit /// @notice This is the main contract for tBTC. It is the state machine that /// (through various libraries) handles bitcoin funding, bitcoin-spv /// proofs, redemption, liquidation, and fraud logic. /// @dev This contract presents a public API that exposes the following /// libraries: /// /// - `DepositFunding` /// - `DepositLiquidaton` /// - `DepositRedemption`, /// - `DepositStates` /// - `DepositUtils` /// - `OutsourceDepositLogging` /// - `TBTCConstants` /// /// Where these libraries require deposit state, this contract's state /// variable `self` is used. `self` is a struct of type /// `DepositUtils.Deposit` that contains all aspects of the deposit state /// itself. contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; /// @dev Deposit should only be _constructed_ once. New deposits are created /// using the `DepositFactory.createDeposit` method, and are clones of /// the constructed deposit. The factory will set the initial values /// for a new clone using `initializeDeposit`. constructor () public { // The constructed Deposit will never be used, so the deposit factory // address can be anything. Clones are updated as per above. initialize(address(0xdeadbeef)); } /// @notice Deposits do not accept arbitrary ETH. function () external payable { require(msg.data.length == 0, "Deposit contract was called with unknown function selector."); } //----------------------------- METADATA LOOKUP ------------------------------// /// @notice Get this deposit's BTC lot size in satoshis. /// @return uint64 lot size in satoshis. function lotSizeSatoshis() external view returns (uint64){ return self.lotSizeSatoshis; } /// @notice Get this deposit's lot size in TBTC. /// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale /// to 18 decimal places. /// @return uint256 lot size in TBTC precision (max 18 decimal places). function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the signer fee for this deposit, in TBTC. /// @dev This is the one-time fee required by the signers to perform the /// tasks needed to maintain a decentralized and trustless model for /// tBTC. It is a percentage of the deposit's lot size. /// @return Fee amount in TBTC. function signerFeeTbtc() external view returns (uint256) { return self.signerFeeTbtc(); } /// @notice Get the integer representing the current state. /// @dev We implement this because contracts don't handle foreign enums /// well. See `DepositStates` for more info on states. /// @return The 0-indexed state from the DepositStates enum. function currentState() external view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, false otherwise. function inActive() external view returns (bool) { return self.inActive(); } /// @notice Get the contract address of the BondedECDSAKeep associated with /// this Deposit. /// @dev The keep contract address is saved on Deposit initialization. /// @return Address of the Keep contract. function keepAddress() external view returns (address) { return self.keepAddress; } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value accuracy is not guaranteed since block.timestmap can be /// lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at /// term. function remainingTerm() external view returns(uint256){ return self.remainingTerm(); } /// @notice Get the current collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value the /// signers currently must hold as bond. /// @return The current collateralization level for this deposit. function collateralizationPercentage() external view returns (uint256) { return self.collateralizationPercentage(); } /// @notice Get the initial collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value /// the signers hold initially. It is set at creation time. /// @return The initial collateralization level for this deposit. function initialCollateralizedPercent() external view returns (uint16) { return self.initialCollateralizedPercent; } /// @notice Get the undercollateralization level for this Deposit. /// @dev This collateralization level is semi-critical. If the /// collateralization level falls below this percentage the Deposit can /// be courtesy-called by calling `notifyCourtesyCall`. This value /// represents the percentage of the backing BTC value the signers must /// hold as bond in order to not be undercollateralized. It is set at /// creation time. Note that the value for new deposits in TBTCSystem /// can be changed by governance, but the value for a particular /// deposit is static once the deposit is created. /// @return The undercollateralized level for this deposit. function undercollateralizedThresholdPercent() external view returns (uint16) { return self.undercollateralizedThresholdPercent; } /// @notice Get the severe undercollateralization level for this Deposit. /// @dev This collateralization level is critical. If the collateralization /// level falls below this percentage the Deposit can get liquidated. /// This value represents the percentage of the backing BTC value the /// signers must hold as bond in order to not be severely /// undercollateralized. It is set at creation time. Note that the /// value for new deposits in TBTCSystem can be changed by governance, /// but the value for a particular deposit is static once the deposit /// is created. /// @return The severely undercollateralized level for this deposit. function severelyUndercollateralizedThresholdPercent() external view returns (uint16) { return self.severelyUndercollateralizedThresholdPercent; } /// @notice Get the value of the funding UTXO. /// @dev This call will revert if the deposit is not in a state where the /// UTXO info should be valid. In particular, before funding proof is /// successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value /// would not be valid. /// @return The value of the funding UTXO in satoshis. function utxoValue() external view returns (uint256){ require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return self.utxoValue(); } /// @notice Returns information associated with the funding UXTO. /// @dev This call will revert if the deposit is not in a state where the /// funding info should be valid. In particular, before funding proof /// is successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of /// these values are set or valid. /// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint). function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) { require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint); } /// @notice Calculates the amount of value at auction right now. /// @dev This call will revert if the deposit is not in a state where an /// auction is currently in progress. /// @return The value in wei that would be received in exchange for the /// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction` /// were called at the time this function is called. function auctionValue() external view returns (uint256) { require( self.inSignerLiquidation(), "Deposit has no funds currently at auction" ); return self.auctionValue(); } /// @notice Get caller's ETH withdraw allowance. /// @dev Generally ETH is only available to withdraw after the deposit /// reaches a closed state. The amount reported is for the sender, and /// can be withdrawn using `withdrawFunds` if the deposit is in an end /// state. /// @return The withdraw allowance in wei. function withdrawableAmount() external view returns (uint256) { return self.getWithdrawableAmount(); } //------------------------------ FUNDING FLOW --------------------------------// /// @notice Notify the contract that signing group setup has timed out if /// retrieveSignerPubkey is not successfully called within the /// allotted time. /// @dev This is considered a signer fault, and the signers' bonds are used /// to make the deposit setup fee available for withdrawal by the TDT /// holder as a refund. The remainder of the signers' bonds are /// returned to the bonding pool and the signers are released from any /// further responsibilities. Reverts if the deposit is not awaiting /// signer setup or if the signing group formation timeout has not /// elapsed. function notifySignerSetupFailed() external { self.notifySignerSetupFailed(); } /// @notice Notify the contract that the ECDSA keep has generated a public /// key so the deposit contract can pull it in. /// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a /// RegisteredPubkey event with the two components. Reverts if the /// deposit is not awaiting signer setup, if the generated public key /// is unset or has incorrect length, or if the public key has a 0 /// X or Y value. function retrieveSignerPubkey() external { self.retrieveSignerPubkey(); } /// @notice Notify the contract that the funding phase of the deposit has /// timed out if `provideBTCFundingProof` is not successfully called /// within the allotted time. Any sent BTC is left under control of /// the signer group, and the funder can use `requestFunderAbort` to /// request an at-signer-discretion return of any BTC sent to a /// deposit that has been notified of a funding timeout. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Emits a SetupFailed event. /// Reverts if the funding timeout has not yet elapsed, or if the /// deposit is not currently awaiting funding proof. function notifyFundingTimedOut() external { self.notifyFundingTimedOut(); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests the return of a sent UTXO to _abortOutputScript. It /// imposes no requirements on the signing group. Signers should /// send their UTXO to the requested output script, but do so at /// their discretion and with no penalty for failing to do so. This /// can be used for example when a UTXO is sent that is the wrong /// size for the lot. /// @dev This is a self-admitted funder fault, and is only be callable by /// the TDT holder. This function emits the FunderAbortRequested event, /// but stores no additional state. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( self.depositOwner() == msg.sender, "Only TDT holder can request funder abort" ); self.requestFunderAbort(_abortOutputScript); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key to prove fraud during funding. Note that during /// funding no signature has been requested from the signers, so /// any signature is effectively fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Anyone may submit a funding proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// to the signer-controlled private key corresopnding to this /// deposit. This will move the deposit into an active state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector /// (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //---------------------------- LIQUIDATION FLOW ------------------------------// /// @notice Notify the contract that the signers are undercollateralized. /// @dev This call will revert if the signers are not in fact /// undercollateralized according to the price feed. After /// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and /// regular abort liquidation occurs; see /// `notifyCourtesyTimedOut`. function notifyCourtesyCall() external { self.notifyCourtesyCall(); } /// @notice Notify the contract that the signers' bond value has recovered /// enough to be considered sufficiently collateralized. /// @dev This call will revert if collateral is still below the /// undercollateralized threshold according to the price feed. function exitCourtesyCall() external { self.exitCourtesyCall(); } /// @notice Notify the contract that the courtesy period has expired and the /// deposit should move into liquidation. /// @dev This call will revert if the courtesy call period has not in fact /// expired or is not in the courtesy call state. Courtesy call /// expiration is treated as an abort, and is handled by seizing signer /// bonds and putting them up for auction for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for 50% of any bond left after the /// auction is completed. function notifyCourtesyCallExpired() external { self.notifyCourtesyCallExpired(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @dev This call will revert if the signers are not in fact severely /// undercollateralized according to the price feed. Severe /// undercollateralization is treated as an abort, and is handled by /// seizing signer bonds and putting them up for auction in exchange /// for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and is /// eligible for 50% of any bond left after the auction is completed. function notifyUndercollateralizedLiquidation() external { self.notifyUndercollateralizedLiquidation(); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key that was not requested to prove fraud. A redemption /// request and a redemption fee increase are the only ways to /// request a signature from the signers. /// @dev This call will revert if the underlying keep cannot verify that /// there was fraud. Fraud is handled by seizing signer bonds and /// putting them up for auction in exchange for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for any bond left after the auction is /// completed. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Notify the contract that the signers have failed to produce a /// signature for a redemption request in the allotted time. /// @dev This is considered an abort, and is punished by seizing signer /// bonds and putting them up for auction. Emits a LiquidationStarted /// event and a Liquidated event and sends the full signer bond to the /// redeemer. Reverts if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. The caller /// is captured as the liquidation initiator, and is eligible for 50% /// of any bond left after the auction is completed. function notifyRedemptionSignatureTimedOut() external { self.notifyRedemptionSignatureTimedOut(); } /// @notice Notify the contract that the deposit has failed to receive a /// redemption proof in the allotted time. /// @dev This call will revert if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. This is /// considered an abort, and is punished by seizing signer bonds and /// putting them up for auction for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and /// is eligible for 50% of any bond left after the auction is /// completed. function notifyRedemptionProofTimedOut() external { self.notifyRedemptionProofTimedOut(); } /// @notice Closes an auction and purchases the signer bonds by transferring /// the lot size in TBTC to the redeemer, if there is one, or to the /// TDT holder if not. Any bond amount that is not currently up for /// auction is either made available for the liquidation initiator /// to withdraw (for fraud) or split 50-50 between the initiator and /// the signers (for abort or collateralization issues). /// @dev The amount of ETH given for the transferred TBTC can be read using /// the `auctionValue` function; note, however, that the function's /// value is only static during the specific block it is queried, as it /// varies by block timestamp. function purchaseSignerBondsAtAuction() external { self.purchaseSignerBondsAtAuction(); } //---------------------------- REDEMPTION FLOW -------------------------------// /// @notice Get TBTC amount required for redemption by a specified /// _redeemer. /// @dev This call will revert if redemption is not possible by _redeemer. /// @param _redeemer The deposit redeemer whose TBTC requirement is being /// requested. /// @return The amount in TBTC needed by the `_redeemer` to redeem the /// deposit. function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false); return tbtcPayment; } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's owner (TDT holder). /// @param _redeemer The assumed owner of the deposit's TDT . /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true); return tbtcPayment; } /// @notice Requests redemption of this deposit, meaning the transmission, /// by the signers, of the deposit's UTXO to the specified Bitocin /// output script. Requires approving the deposit to spend the /// amount of TBTC needed to redeem. /// @dev The amount of TBTC needed to redeem can be looked up using the /// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement` /// functions. /// @param _outputValueBytes The 8-byte little-endian output size. The /// difference between this value and the lot size of the deposit /// will be paid as a fee to the Bitcoin miners when the signed /// transaction is broadcast. /// @param _redeemerOutputScript The redeemer's length-prefixed output /// script. function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters self.requestRedemption(_outputValueBytes, _redeemerOutputScript); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this function is not called /// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT` /// seconds of a redemption request or fee increase being received. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 /// curve's order. function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) external { self.provideRedemptionSignature(_v, _r, _s); } /// @notice Anyone may request a signature for a transaction with an /// increased Bitcoin transaction fee. /// @dev This call will revert if the fee is already at its maximum, or if /// the new requested fee is not a multiple of the initial requested /// fee. Transaction fees can only be bumped by the amount of the /// initial requested fee. Calling this sends the deposit back to /// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers /// to `provideRedemptionSignature` for the new output value in a /// timely fashion. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) external { self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may submit a redemption proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// from the signer-controlled private key corresponding to this /// deposit to the requested redemption output script. This will /// move the deposit into a redeemed state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. Signers can have their bonds seized if this is not /// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of /// a redemption signature being provided. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //--------------------------- MUTATING HELPERS -------------------------------// /// @notice This function can only be called by the deposit factory; use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev Initializes a new deposit clone with the base state for the /// deposit. /// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`. /// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`. /// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in /// `TBTCDepositToken`. /// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in /// `FeeRebateToken`. /// @param _vendingMachineAddress `VendingMachine` address. More info in /// `VendingMachine`. /// @param _lotSizeSatoshis The minimum amount of satoshi the funder is /// required to send. This is also the amount of /// TBTC the TDT holder will be eligible to mint: /// (10**7 satoshi == 0.1 BTC == 0.1 TBTC). function initializeDeposit( ITBTCSystem _tbtcSystem, TBTCToken _tbtcToken, IERC721 _tbtcDepositToken, FeeRebateToken _feeRebateToken, address _vendingMachineAddress, uint64 _lotSizeSatoshis ) public onlyFactory payable { self.tbtcSystem = _tbtcSystem; self.tbtcToken = _tbtcToken; self.tbtcDepositToken = _tbtcDepositToken; self.feeRebateToken = _feeRebateToken; self.vendingMachineAddress = _vendingMachineAddress; self.initialize(_lotSizeSatoshis); } /// @notice This function can only be called by the vending machine. /// @dev Performs the same action as requestRedemption, but transfers /// ownership of the deposit to the specified _finalRecipient. Used as /// a utility helper for the vending machine's shortcut /// TBTC->redemption path. /// @param _outputValueBytes The 8-byte little-endian output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters require( msg.sender == self.vendingMachineAddress, "Only the vending machine can call transferAndRequestRedemption" ); self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); } /// @notice Withdraw the ETH balance of the deposit allotted to the caller. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds() external { self.withdrawFunds(); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; library DepositLiquidation { using BTCUtils for bytes; using BytesLib for bytes; using SafeMath for uint256; using SafeMath for uint64; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Notifies the keep contract of fraud. Reverts if not fraud. /// @dev Calls out to the keep contract. this could get expensive if preimage /// is large. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function submitSignatureFraud( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); } /// @notice Determines the collateralization percentage of the signing group. /// @dev Compares the bond value and lot value. /// @param _d Deposit storage pointer. /// @return Collateralization percentage as uint. function collateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) { // Determine value of the lot in wei uint256 _satoshiPrice = _d.fetchBitcoinPrice(); uint64 _lotSizeSatoshis = _d.lotSizeSatoshis; uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice); // Amount of wei the signers have uint256 _bondValue = _d.fetchBondAmount(); // This converts into a percentage return (_bondValue.mul(100).div(_lotValue)); } /// @dev Starts signer liquidation by seizing signer bonds. /// If the deposit is currently being redeemed, the redeemer /// receives the full bond value; otherwise, a falling price auction /// begins to buy 1 TBTC in exchange for a portion of the seized bonds; /// see purchaseSignerBondsAtAuction(). /// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason. /// @param _d Deposit storage pointer. function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal { _d.logStartedLiquidation(_wasFraud); uint256 seized = _d.seizeSignerBonds(); address redeemerAddress = _d.redeemerAddress; // Reclaim used state for gas savings _d.redemptionTeardown(); // If we see fraud in the redemption flow, we shouldn't go to auction. // Instead give the full signer bond directly to the redeemer. if (_d.inRedemption() && _wasFraud) { _d.setLiquidated(); _d.enableWithdrawal(redeemerAddress, seized); _d.logLiquidated(); return; } _d.liquidationInitiator = msg.sender; _d.liquidationInitiated = block.timestamp; // Store the timestamp for auction if(_wasFraud){ _d.setFraudLiquidationInProgress(); } else{ _d.setLiquidationInProgress(); } } /// @notice Anyone can provide a signature that was not requested to prove fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( !_d.inFunding(), "Use provideFundingECDSAFraudProof instead" ); require( !_d.inSignerLiquidation(), "Signer liquidation already in progress" ); require(!_d.inEndState(), "Contract has halted"); submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage); startLiquidation(_d, true); } /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud. /// @dev For interface, reading auctionValue will give a past value. the current is better. /// @param _d Deposit storage pointer. function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) external { bool _wasFraud = _d.inFraudLiquidationInProgress(); require(_d.inSignerLiquidation(), "No active auction"); _d.setLiquidated(); _d.logLiquidated(); // Send the TBTC to the redeemer if they exist, otherwise to the TDT // holder. If the TDT holder is the Vending Machine, burn it to maintain // the peg. This is because, if there is a redeemer set here, the TDT // holder has already been made whole at redemption request time. address tbtcRecipient = _d.redeemerAddress; if (tbtcRecipient == address(0)) { tbtcRecipient = _d.depositOwner(); } uint256 lotSizeTbtc = _d.lotSizeTbtc(); require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt"); if(tbtcRecipient == _d.vendingMachineAddress){ _d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size } else{ _d.tbtcToken.transferFrom(msg.sender, tbtcRecipient, lotSizeTbtc); } // Distribute funds to auction buyer uint256 valueToDistribute = _d.auctionValue(); _d.enableWithdrawal(msg.sender, valueToDistribute); // Send any TBTC left to the Fee Rebate Token holder _d.distributeFeeRebate(); // For fraud, pay remainder to the liquidation initiator. // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1, // division will yield a 0 value which causes a revert; instead, // we simply ignore such a tiny amount and leave some wei dust in escrow uint256 contractEthBalance = address(this).balance; address payable initiator = _d.liquidationInitiator; if (initiator == address(0)){ initiator = address(0xdead); } if (contractEthBalance > valueToDistribute + 1) { uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute); if (_wasFraud) { _d.enableWithdrawal(initiator, remainingUnallocated); } else { // There will always be a liquidation initiator. uint256 split = remainingUnallocated.div(2); _d.pushFundsToKeepGroup(split); _d.enableWithdrawal(initiator, remainingUnallocated.sub(split)); } } } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inActive(), "Can only courtesy call from active state"); require(collateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral"); _d.courtesyCallInitiated = block.timestamp; _d.setCourtesyCall(); _d.logCourtesyCalled(); } /// @notice Goes from courtesy call to active. /// @dev Only callable if collateral is sufficient and the deposit is not expiring. /// @param _d Deposit storage pointer. function exitCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not currently in courtesy call"); require(collateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized"); _d.setActive(); _d.logExitedCourtesyCall(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) external { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(collateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); } /// @notice Notifies the contract that the courtesy period has elapsed. /// @dev This is treated as an abort, rather than fraud. /// @param _d Deposit storage pointer. function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not in a courtesy call period"); require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed"); startLiquidation(_d, false); } } pragma solidity ^0.5.10; /** @title BitcoinSPV */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; // The target at minimum Difficulty. Also the target of the genesis block uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /* ***** */ /* UTILS */ /* ***** */ /// @notice Determines the length of a VarInt in bytes /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length /// @param _flag The first byte of a VarInt /// @return The number of non-flag bytes in the VarInt function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) { if (uint8(_flag[0]) == 0xff) { return 8; // one-byte flag, 8 bytes data } if (uint8(_flag[0]) == 0xfe) { return 4; // one-byte flag, 4 bytes data } if (uint8(_flag[0]) == 0xfd) { return 2; // one-byte flag, 2 bytes data } return 0; // flag is data } /// @notice Parse a VarInt into its data length and the number it represents /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes. /// Caller SHOULD explicitly handle this case (or bubble it up) /// @param _b A byte-string starting with a VarInt /// @return number of bytes in the encoding (not counting the tag), the encoded int function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) { uint8 _dataLen = determineVarIntDataLength(_b); if (_dataLen == 0) { return (0, uint8(_b[0])); } if (_b.length < 1 + _dataLen) { return (ERR_BAD_ARG, 0); } uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen))); return (_dataLen, _number); } /// @notice Changes the endianness of a byte array /// @dev Returns a new, backwards, bytes /// @param _b The bytes to reverse /// @return The reversed bytes function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) { bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } /// @notice Changes the endianness of a uint256 /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel /// @param _b The unsigned integer to reverse /// @return The reversed value function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /// @notice Converts big-endian bytes to a uint /// @dev Traverses the byte array and sums the bytes /// @param _b The big-endian bytes-encoded integer /// @return The integer representation function bytesToUint(bytes memory _b) internal pure returns (uint256) { uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } /// @notice Get the last _num bytes from a byte array /// @param _b The byte array to slice /// @param _num The number of bytes to extract from the end /// @return The last _num bytes of _b function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { uint256 _start = _b.length.sub(_num); return _b.slice(_start, _num); } /// @notice Implements bitcoin's hash160 (rmd160(sha2())) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash160(bytes memory _b) internal pure returns (bytes memory) { return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash256(bytes memory _b) internal pure returns (bytes32) { return sha256(abi.encodePacked(sha256(_b))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev sha2 is precompiled smart contract located at address(2) /// @param _b The pre-image /// @return The digest function hash256View(bytes memory _b) internal view returns (bytes32 res) { // solium-disable-next-line security/no-inline-assembly assembly { let ptr := mload(0x40) pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32)) pop(staticcall(gas, 2, ptr, 32, ptr, 32)) res := mload(ptr) } } /* ************ */ /* Legacy Input */ /* ************ */ /// @notice Extracts the nth input from the vin (0-indexed) /// @dev Iterates over the vin. If you need to extract several, write a custom function /// @param _vin The vin as a tightly-packed byte array /// @param _index The 0-indexed location of the input to extract /// @return The input as a byte array function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nIns, "Vin read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); _offset = _offset + _len; } _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _vin.slice(_offset, _len); } /// @notice Determines whether an input is legacy /// @dev False if no scriptSig, otherwise True /// @param _input The input /// @return True for legacy, False for witness function isLegacyInput(bytes memory _input) internal pure returns (bool) { return _input.keccak256Slice(36, 1) != keccak256(hex"00"); } /// @notice Determines the length of a scriptSig in an input /// @dev Will return 0 if passed a witness input. /// @param _input The LEGACY input /// @return The length of the script sig function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) { if (_input.length < 37) { return (ERR_BAD_ARG, 0); } bytes memory _afterOutpoint = _input.slice(36, _input.length - 36); uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint); return (_varIntDataLen, _scriptSigLen); } /// @notice Determines the length of an input from its scriptSig /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence /// @param _input The input /// @return The length of the input in bytes function determineInputLength(bytes memory _input) internal pure returns (uint256) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The LEGACY input /// @return The sequence bytes (LE uint) function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } /// @notice Extracts the sequence from the input /// @dev Sequence is a 4-byte little-endian number /// @param _input The LEGACY input /// @return The sequence number (big-endian uint) function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLELegacy(_input); bytes memory _beSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_beSequence)); } /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx /// @dev Will return hex"00" if passed a witness input /// @param _input The LEGACY input /// @return The length-prepended scriptSig function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen); } /* ************* */ /* Witness Input */ /* ************* */ /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The WITNESS input /// @return The sequence bytes (LE uint) function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(37, 4); } /// @notice Extracts the sequence from the input in a tx /// @dev Sequence is a 4-byte little-endian number /// @param _input The WITNESS input /// @return The sequence number (big-endian uint) function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLEWitness(_input); bytes memory _inputeSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_inputeSequence)); } /// @notice Extracts the outpoint from the input in a tx /// @dev 32-byte tx id with 4-byte index /// @param _input The input /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index) function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(0, 36); } /// @notice Extracts the outpoint tx id from an input /// @dev 32-byte tx id /// @param _input The input /// @return The tx id (little-endian bytes) function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) { return _input.slice(0, 32).toBytes32(); } /// @notice Extracts the LE tx input index from the input in a tx /// @dev 4-byte tx index /// @param _input The input /// @return The tx index (little-endian bytes) function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(32, 4); } /* ****** */ /* Output */ /* ****** */ /// @notice Determines the length of an output /// @dev Works with any properly formatted output /// @param _output The output /// @return The length indicated by the prefix, error if invalid length function determineOutputLength(bytes memory _output) internal pure returns (uint256) { if (_output.length < 9) { return ERR_BAD_ARG; } bytes memory _afterValue = _output.slice(8, _output.length - 8); uint256 _varIntDataLen; uint256 _scriptPubkeyLength; (_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } // 8-byte value, 1-byte for tag itself return 8 + 1 + _varIntDataLen + _scriptPubkeyLength; } /// @notice Extracts the output at a given index in the TxOuts vector /// @dev Iterates over the vout. If you need to extract multiple, write a custom function /// @param _vout The _vout to extract from /// @param _index The 0-indexed location of the output to extract /// @return The specified output function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nOuts, "Vout read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); _offset += _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); return _vout.slice(_offset, _len); } /// @notice Extracts the value bytes from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value as LE bytes function extractValueLE(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(0, 8); } /// @notice Extracts the value from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value function extractValue(bytes memory _output) internal pure returns (uint64) { bytes memory _leValue = extractValueLE(_output); bytes memory _beValue = reverseEndianness(_leValue); return uint64(bytesToUint(_beValue)); } /// @notice Extracts the data from an op return output /// @dev Returns hex"" if no data or not an op return /// @param _output The output /// @return Any data contained in the opreturn output, null if not an op return function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) { if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.slice(10, 1); return _output.slice(11, bytesToUint(_dataLen)); } /// @notice Extracts the hash from the output script /// @dev Determines type by the length prefix and validates format /// @param _output The output /// @return The hash committed to by the pk_script, or null for errors function extractHash(bytes memory _output) internal pure returns (bytes memory) { uint8 _scriptLen = uint8(_output[8]); // don't have to worry about overflow here. // if _scriptLen + 9 overflows, then output.length would have to be < 9 // for this check to pass. if it's < 9, then we errored when assigning // _scriptLen if (_scriptLen + 9 != _output.length) { return hex""; } if (uint8(_output[9]) == 0) { if (_scriptLen < 2) { return hex""; } uint256 _payloadLen = uint8(_output[10]); // Check for maliciously formatted witness outputs. // No need to worry about underflow as long b/c of the `< 2` check if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) { return hex""; } return _output.slice(11, _payloadLen); } else { bytes32 _tag = _output.keccak256Slice(8, 3); // p2pkh if (_tag == keccak256(hex"1976a9")) { // Check for maliciously formatted p2pkh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[11]) != 0x14 || _output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) { return hex""; } return _output.slice(12, 20); //p2sh } else if (_tag == keccak256(hex"17a914")) { // Check for maliciously formatted p2sh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[_output.length - 1]) != 0x87) { return hex""; } return _output.slice(11, 20); } } return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */ } /* ********** */ /* Witness TX */ /* ********** */ /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vin Raw bytes length-prefixed input vector /// @return True if it represents a validly formatted vin function validateVin(bytes memory _vin) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); // Not valid if it says there are too many or no inputs if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nIns; i++) { // If we're at the end, but still expect more if (_offset >= _vin.length) { return false; } // Grab the next input and determine its length. bytes memory _next = _vin.slice(_offset, _vin.length - _offset); uint256 _nextLen = determineInputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } // Increase the offset by that much _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vin.length; } /// @notice Checks that the vout passed up is properly formatted /// @dev Consider a vout with a valid scriptpubkey /// @param _vout Raw bytes length-prefixed output vector /// @return True if it represents a validly formatted vout function validateVout(bytes memory _vout) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); // Not valid if it says there are too many or no outputs if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nOuts; i++) { // If we're at the end, but still expect more if (_offset >= _vout.length) { return false; } // Grab the next output and determine its length. // Increase the offset by that much bytes memory _next = _vout.slice(_offset, _vout.length - _offset); uint256 _nextLen = determineOutputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vout.length; } /* ************ */ /* Block Header */ /* ************ */ /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (little-endian) function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(36, 32); } /// @notice Extracts the target from a block header /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _header The header /// @return The target threshold function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } /// @notice Calculate difficulty from the difficulty 1 target and current target /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _target The current target /// @return The block difficulty (bdiff) function calculateDifficulty(uint256 _target) internal pure returns (uint256) { // Difficulty 1 calculated from 0x1d00ffff return DIFF1_TARGET.div(_target); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (little-endian) function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (little-endian bytes) function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (uint) function extractTimestamp(bytes memory _header) internal pure returns (uint32) { return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header)))); } /// @notice Extracts the expected difficulty from a block header /// @dev Does NOT verify the work /// @param _header The header /// @return The difficulty as an integer function extractDifficulty(bytes memory _header) internal pure returns (uint256) { return calculateDifficulty(extractTarget(_header)); } /// @notice Concatenates and hashes two inputs for merkle proving /// @param _a The first hash /// @param _b The second hash /// @return The double-sha256 of the concatenated hashes function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { return hash256(abi.encodePacked(_a, _b)); } /// @notice Verifies a Bitcoin-style merkle tree /// @dev Leaves are 0-indexed. /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root /// @param _index The index of the leaf /// @return true if the proof is valid, else false function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) { // Not an even number of hashes if (_proof.length % 32 != 0) { return false; } // Special case for coinbase-only blocks if (_proof.length == 32) { return true; } // Should never occur if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32(); bytes32 _current = _proof.slice(0, 32).toBytes32(); for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current)); } else { _current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } /* NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72 NB: We get a full-bitlength target from this. For comparison with header-encoded targets we need to mask it with the header target e.g. (full & truncated) == truncated */ /// @notice performs the bitcoin difficulty retarget /// @dev implements the Bitcoin algorithm precisely /// @param _previousTarget the target of the previous period /// @param _firstTimestamp the timestamp of the first block in the difficulty period /// @param _secondTimestamp the timestamp of the last block in the difficulty period /// @return the new period's target threshold function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); // Normalize ratio to factor of 4 if very long or very short if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } /* NB: high targets e.g. ffff0020 can cause overflows here so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue */ uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); } } pragma solidity ^0.5.10; /* https://github.com/GNSPS/solidity-bytes-utils/ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <https://unlicense.org> */ /** @title BytesLib **/ /** @author https://github.com/GNSPS **/ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) { if (_length == 0) { return hex""; } uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { // Alloc bytes array with additional 32 bytes afterspace and assign it's size res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length) // Compute distance between source and destination pointers let diff := sub(res, add(_bytes, _start)) for { let src := add(add(_bytes, 32), _start) let end := add(src, _length) } lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) } } } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { uint _totalLen = _start + 20; require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint _totalLen = _start + 32; require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } function toBytes32(bytes memory _source) pure internal returns (bytes32 result) { if (_source.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { result := keccak256(add(add(_bytes, 32), _start), _length) } } } pragma solidity ^0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b, "Overflow during multiplication."); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } pragma solidity 0.5.17; import {DepositUtils} from "./DepositUtils.sol"; library DepositStates { enum States { // DOES NOT EXIST YET START, // FUNDING FLOW AWAITING_SIGNER_SETUP, AWAITING_BTC_FUNDING_PROOF, // FAILED SETUP FAILED_SETUP, // ACTIVE ACTIVE, // includes courtesy call // REDEMPTION FLOW AWAITING_WITHDRAWAL_SIGNATURE, AWAITING_WITHDRAWAL_PROOF, REDEEMED, // SIGNER LIQUIDATION FLOW COURTESY_CALL, FRAUD_LIQUIDATION_IN_PROGRESS, LIQUIDATION_IN_PROGRESS, LIQUIDATED } /// @notice Check if the contract is currently in the funding flow. /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the funding flow else False. function inFunding(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_SIGNER_SETUP) || _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF) ); } /// @notice Check if the contract is currently in the signer liquidation flow. /// @dev This could be caused by fraud, or by an unfilled margin call. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the liquidaton flow else False. function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS) || _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS) ); } /// @notice Check if the contract is currently in the redepmtion flow. /// @dev This checks on the redemption flow, not the REDEEMED termination state. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the redemption flow else False. function inRedemption(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE) || _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF) ); } /// @notice Check if the contract has halted. /// @dev This checks on any halt state, regardless of triggering circumstances. /// @param _d Deposit storage pointer. /// @return True if contract has halted permanently. function inEndState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATED) || _d.currentState == uint8(States.REDEEMED) || _d.currentState == uint8(States.FAILED_SETUP) ); } /// @notice Check if the contract is available for a redemption request. /// @dev Redemption is available from active and courtesy call. /// @param _d Deposit storage pointer. /// @return True if available, False otherwise. function inRedeemableState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.ACTIVE) || _d.currentState == uint8(States.COURTESY_CALL) ); } /// @notice Check if the contract is currently in the start state (awaiting setup). /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the start state else False. function inStart(DepositUtils.Deposit storage _d) public view returns (bool) { return (_d.currentState == uint8(States.START)); } function inAwaitingSignerSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_SIGNER_SETUP); } function inAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF); } function inFailedSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FAILED_SETUP); } function inActive(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.ACTIVE); } function inAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function inAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF); } function inRedeemed(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.REDEEMED); } function inCourtesyCall(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.COURTESY_CALL); } function inFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function inLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS); } function inLiquidated(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATED); } function setAwaitingSignerSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_SIGNER_SETUP); } function setAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_BTC_FUNDING_PROOF); } function setFailedSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FAILED_SETUP); } function setActive(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.ACTIVE); } function setAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function setAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_PROOF); } function setRedeemed(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.REDEEMED); } function setCourtesyCall(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.COURTESY_CALL); } function setFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function setLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATION_IN_PROGRESS); } function setLiquidated(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATED); } } pragma solidity 0.5.17; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; library DepositUtils { using SafeMath for uint256; using SafeMath for uint64; using BytesLib for bytes; using BTCUtils for bytes; using BTCUtils for uint256; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositStates for DepositUtils.Deposit; struct Deposit { // SET DURING CONSTRUCTION ITBTCSystem tbtcSystem; TBTCToken tbtcToken; IERC721 tbtcDepositToken; FeeRebateToken feeRebateToken; address vendingMachineAddress; uint64 lotSizeSatoshis; uint8 currentState; uint16 signerFeeDivisor; uint16 initialCollateralizedPercent; uint16 undercollateralizedThresholdPercent; uint16 severelyUndercollateralizedThresholdPercent; uint256 keepSetupFee; // SET ON FRAUD uint256 liquidationInitiated; // Timestamp of when liquidation starts uint256 courtesyCallInitiated; // When the courtesy call is issued address payable liquidationInitiator; // written when we request a keep address keepAddress; // The address of our keep contract uint256 signingGroupRequestedAt; // timestamp of signing group request // written when we get a keep result uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey // INITIALLY WRITTEN BY REDEMPTION FLOW address payable redeemerAddress; // The redeemer's address, used as fallback for fraud in redemption bytes redeemerOutputScript; // The redeemer output script uint256 initialRedemptionFee; // the initial fee as requested uint256 latestRedemptionFee; // the fee currently required by a redemption transaction uint256 withdrawalRequestTime; // the most recent withdrawal request timestamp bytes32 lastRequestedDigest; // the digest most recently requested for signing // written when we get funded bytes8 utxoValueBytes; // LE uint. the size of the deposit UTXO in satoshis uint256 fundedAt; // timestamp when funding proof was received bytes utxoOutpoint; // the 36-byte outpoint of the custodied UTXO /// @dev Map of ETH balances an address can withdraw after contract reaches ends-state. mapping(address => uint256) withdrawableAmounts; /// @dev Map of timestamps representing when transaction digests were approved for signing mapping (bytes32 => uint256) approvedDigests; } /// @notice Closes keep associated with the deposit. /// @dev Should be called when the keep is no longer needed and the signing /// group can disband. function closeKeep(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.closeKeep(); } /// @notice Gets the current block difficulty. /// @dev Calls the light relay and gets the current block difficulty. /// @return The difficulty. function currentBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayCurrentDifficulty(); } /// @notice Gets the previous block difficulty. /// @dev Calls the light relay and gets the previous block difficulty. /// @return The difficulty. function previousBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayPreviousDifficulty(); } /// @notice Evaluates the header difficulties in a proof. /// @dev Uses the light oracle to source recent difficulty. /// @param _bitcoinHeaders The header chain to evaluate. /// @return True if acceptable, otherwise revert. function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); } /// @notice Syntactically check an SPV proof for a bitcoin transaction with its hash (ID). /// @dev Stateless SPV Proof verification documented elsewhere (see https://github.com/summa-tx/bitcoin-spv). /// @param _d Deposit storage pointer. /// @param _txId The bitcoin txid of the tx that is purportedly included in the header chain. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function checkProofFromTxId( Deposit storage _d, bytes32 _txId, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view{ require( _txId.prove( _bitcoinHeaders.extractMerkleRootLE().toBytes32(), _merkleProof, _txIndexInBlock ), "Tx merkle proof is not valid for provided header and txId"); evaluateProofDifficulty(_d, _bitcoinHeaders); } /// @notice Find and validate funding output in transaction output vector using the index. /// @dev Gets `_fundingOutputIndex` output from the output vector and validates if it is /// a p2wpkh output with public key hash matching this deposit's public key hash. /// @param _d Deposit storage pointer. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC outputs. /// @param _fundingOutputIndex Index of funding output in _txOutputVector. /// @return Funding value. function findAndParseFundingOutput( DepositUtils.Deposit storage _d, bytes memory _txOutputVector, uint8 _fundingOutputIndex ) public view returns (bytes8) { bytes8 _valueBytes; bytes memory _output; // Find the output paying the signer PKH _output = _txOutputVector.extractOutputAtIndex(_fundingOutputIndex); require( keccak256(_output.extractHash()) == keccak256(abi.encodePacked(signerPKH(_d))), "Could not identify output funding the required public key hash" ); require( _output.length == 31 && _output.keccak256Slice(8, 23) == keccak256(abi.encodePacked(hex"160014", signerPKH(_d))), "Funding transaction output type unsupported: only p2wpkh outputs are supported" ); _valueBytes = bytes8(_output.slice(0, 8).toBytes32()); return _valueBytes; } /// @notice Validates the funding tx and parses information from it. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. /// @return The 8-byte LE UTXO size in satoshi, the 36byte outpoint. function validateAndParseFundingSPVProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view returns (bytes8 _valueBytes, bytes memory _utxoOutpoint){ // not external to allow bytes memory parameters require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes32 txID = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _valueBytes = findAndParseFundingOutput(_d, _txOutputVector, _fundingOutputIndex); require(bytes8LEToUint(_valueBytes) >= _d.lotSizeSatoshis, "Deposit too small"); checkProofFromTxId(_d, txID, _merkleProof, _txIndexInBlock, _bitcoinHeaders); // The utxoOutpoint is the LE txID plus the index of the output as a 4-byte LE int // _fundingOutputIndex is a uint8, so we know it is only 1 byte // Therefore, pad with 3 more bytes _utxoOutpoint = abi.encodePacked(txID, _fundingOutputIndex, hex"000000"); } /// @notice Retreive the remaining term of the deposit /// @dev The return value is not guaranteed since block.timestmap can be lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at term function remainingTerm(DepositUtils.Deposit storage _d) public view returns(uint256){ uint256 endOfTerm = _d.fundedAt.add(TBTCConstants.getDepositTerm()); if(block.timestamp < endOfTerm ) { return endOfTerm.sub(block.timestamp); } return 0; } /// @notice Calculates the amount of value at auction right now. /// @dev We calculate the % of the auction that has elapsed, then scale the value up. /// @param _d Deposit storage pointer. /// @return The value in wei to distribute in the auction at the current time. function auctionValue(Deposit storage _d) external view returns (uint256) { uint256 _elapsed = block.timestamp.sub(_d.liquidationInitiated); uint256 _available = address(this).balance; if (_elapsed > TBTCConstants.getAuctionDuration()) { return _available; } // This should make a smooth flow from base% to 100% uint256 _basePercentage = getAuctionBasePercentage(_d); uint256 _elapsedPercentage = uint256(100).sub(_basePercentage).mul(_elapsed).div(TBTCConstants.getAuctionDuration()); uint256 _percentage = _basePercentage.add(_elapsedPercentage); return _available.mul(_percentage).div(100); } /// @notice Gets the lot size in erc20 decimal places (max 18) /// @return uint256 lot size in 10**18 decimals. function lotSizeTbtc(Deposit storage _d) public view returns (uint256){ return _d.lotSizeSatoshis.mul(TBTCConstants.getSatoshiMultiplier()); } /// @notice Determines the fees due to the signers for work performed. /// @dev Signers are paid based on the TBTC issued. /// @return Accumulated fees in 10**18 decimals. function signerFeeTbtc(Deposit storage _d) public view returns (uint256) { return lotSizeTbtc(_d).div(_d.signerFeeDivisor); } /// @notice Determines the prefix to the compressed public key. /// @dev The prefix encodes the parity of the Y coordinate. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 1-byte prefix for the compressed key. function determineCompressionPrefix(bytes32 _pubkeyY) public pure returns (bytes memory) { if(uint256(_pubkeyY) & 1 == 1) { return hex"03"; // Odd Y } else { return hex"02"; // Even Y } } /// @notice Compresses a public key. /// @dev Converts the 64-byte key to a 33-byte key, bitcoin-style. /// @param _pubkeyX The X coordinate of the public key. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 33-byte compressed pubkey. function compressPubkey(bytes32 _pubkeyX, bytes32 _pubkeyY) public pure returns (bytes memory) { return abi.encodePacked(determineCompressionPrefix(_pubkeyY), _pubkeyX); } /// @notice Returns the packed public key (64 bytes) for the signing group. /// @dev We store it as 2 bytes32, (2 slots) then repack it on demand. /// @return 64 byte public key. function signerPubkey(Deposit storage _d) external view returns (bytes memory) { return abi.encodePacked(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Returns the Bitcoin pubkeyhash (hash160) for the signing group. /// @dev This is used in bitcoin output scripts for the signers. /// @return 20-bytes public key hash. function signerPKH(Deposit storage _d) public view returns (bytes20) { bytes memory _pubkey = compressPubkey(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); bytes memory _digest = _pubkey.hash160(); return bytes20(_digest.toAddress(0)); // dirty solidity hack } /// @notice Returns the size of the deposit UTXO in satoshi. /// @dev We store the deposit as bytes8 to make signature checking easier. /// @return UTXO value in satoshi. function utxoValue(Deposit storage _d) external view returns (uint256) { return bytes8LEToUint(_d.utxoValueBytes); } /// @notice Gets the current price of Bitcoin in Ether. /// @dev Polls the price feed via the system contract. /// @return The current price of 1 sat in wei. function fetchBitcoinPrice(Deposit storage _d) external view returns (uint256) { return _d.tbtcSystem.fetchBitcoinPrice(); } /// @notice Fetches the Keep's bond amount in wei. /// @dev Calls the keep contract to do so. /// @return The amount of bonded ETH in wei. function fetchBondAmount(Deposit storage _d) external view returns (uint256) { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); return _keep.checkBondAmount(); } /// @notice Convert a LE bytes8 to a uint256. /// @dev Do this by converting to bytes, then reversing endianness, then converting to int. /// @return The uint256 represented in LE by the bytes8. function bytes8LEToUint(bytes8 _b) public pure returns (uint256) { return abi.encodePacked(_b).reverseEndianness().bytesToUint(); } /// @notice Gets timestamp of digest approval for signing. /// @dev Identifies entry in the recorded approvals by keep ID and digest pair. /// @param _digest Digest to check approval for. /// @return Timestamp from the moment of recording the digest for signing. /// Returns 0 if the digest was not approved for signing. function wasDigestApprovedForSigning(Deposit storage _d, bytes32 _digest) external view returns (uint256) { return _d.approvedDigests[_digest]; } /// @notice Looks up the Fee Rebate Token holder. /// @return The current token holder if the Token exists. /// address(0) if the token does not exist. function feeRebateTokenHolder(Deposit storage _d) public view returns (address payable) { address tokenHolder = address(0); if(_d.feeRebateToken.exists(uint256(address(this)))){ tokenHolder = address(uint160(_d.feeRebateToken.ownerOf(uint256(address(this))))); } return address(uint160(tokenHolder)); } /// @notice Looks up the deposit beneficiary by calling the tBTC system. /// @dev We cast the address to a uint256 to match the 721 standard. /// @return The current deposit beneficiary. function depositOwner(Deposit storage _d) public view returns (address payable) { return address(uint160(_d.tbtcDepositToken.ownerOf(uint256(address(this))))); } /// @notice Deletes state after termination of redemption process. /// @dev We keep around the redeemer address so we can pay them out. function redemptionTeardown(Deposit storage _d) public { _d.redeemerOutputScript = ""; _d.initialRedemptionFee = 0; _d.withdrawalRequestTime = 0; _d.lastRequestedDigest = bytes32(0); } /// @notice Get the starting percentage of the bond at auction. /// @dev This will return the same value regardless of collateral price. /// @return The percentage of the InitialCollateralizationPercent that will result /// in a 100% bond value base auction given perfect collateralization. function getAuctionBasePercentage(Deposit storage _d) internal view returns (uint256) { return uint256(10000).div(_d.initialCollateralizedPercent); } /// @notice Seize the signer bond from the keep contract. /// @dev we check our balance before and after. /// @return The amount seized in wei. function seizeSignerBonds(Deposit storage _d) internal returns (uint256) { uint256 _preCallBalance = address(this).balance; IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.seizeSignerBonds(); uint256 _postCallBalance = address(this).balance; require(_postCallBalance > _preCallBalance, "No funds received, unexpected"); return _postCallBalance.sub(_preCallBalance); } /// @notice Adds a given amount to the withdraw allowance for the address. /// @dev Withdrawals can only happen when a contract is in an end-state. function enableWithdrawal(DepositUtils.Deposit storage _d, address _withdrawer, uint256 _amount) internal { _d.withdrawableAmounts[_withdrawer] = _d.withdrawableAmounts[_withdrawer].add(_amount); } /// @notice Withdraw caller's allowance. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds(DepositUtils.Deposit storage _d) internal { uint256 available = _d.withdrawableAmounts[msg.sender]; require(_d.inEndState(), "Contract not yet terminated"); require(available > 0, "Nothing to withdraw"); require(address(this).balance >= available, "Insufficient contract balance"); // zero-out to prevent reentrancy _d.withdrawableAmounts[msg.sender] = 0; /* solium-disable-next-line security/no-call-value */ (bool ok,) = msg.sender.call.value(available)(""); require( ok, "Failed to send withdrawable amount to sender" ); } /// @notice Get the caller's withdraw allowance. /// @return The caller's withdraw allowance in wei. function getWithdrawableAmount(DepositUtils.Deposit storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; } /// @notice Distributes the fee rebate to the Fee Rebate Token owner. /// @dev Whenever this is called we are shutting down. function distributeFeeRebate(Deposit storage _d) internal { address rebateTokenHolder = feeRebateTokenHolder(_d); // exit the function if there is nobody to send the rebate to if(rebateTokenHolder == address(0)){ return; } // pay out the rebate if it is available if(_d.tbtcToken.balanceOf(address(this)) >= signerFeeTbtc(_d)) { _d.tbtcToken.transfer(rebateTokenHolder, signerFeeTbtc(_d)); } } /// @notice Pushes ether held by the deposit to the signer group. /// @dev Ether is returned to signing group members bonds. /// @param _ethValue The amount of ether to send. function pushFundsToKeepGroup(Deposit storage _d, uint256 _ethValue) internal { require(address(this).balance >= _ethValue, "Not enough funds to send"); if(_ethValue > 0){ IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.returnPartialSignerBonds.value(_ethValue)(); } } /// @notice Calculate TBTC amount required for redemption by a specified /// _redeemer. If _assumeRedeemerHoldTdt is true, return the /// requirement as if the redeemer holds this deposit's TDT. /// @dev Will revert if redemption is not possible by the current owner and /// _assumeRedeemerHoldsTdt was not set. Setting /// _assumeRedeemerHoldsTdt only when appropriate is the responsibility /// of the caller; as such, this function should NEVER be publicly /// exposed. /// @param _redeemer The account that should be treated as redeeming this /// deposit for the purposes of this calculation. /// @param _assumeRedeemerHoldsTdt If true, the calculation assumes that the /// specified redeemer holds the TDT. If false, the calculation /// checks the deposit owner against the specified _redeemer. Note /// that this parameter should be false for all mutating calls to /// preserve system correctness. /// @return A tuple of the amount the redeemer owes to the deposit to /// initiate redemption, the amount that is owed to the TDT holder /// when redemption is initiated, and the amount that is owed to the /// FRT holder when redemption is initiated. function calculateRedemptionTbtcAmounts( DepositUtils.Deposit storage _d, address _redeemer, bool _assumeRedeemerHoldsTdt ) internal view returns ( uint256 owedToDeposit, uint256 owedToTdtHolder, uint256 owedToFrtHolder ) { bool redeemerHoldsTdt = _assumeRedeemerHoldsTdt || depositOwner(_d) == _redeemer; bool preTerm = remainingTerm(_d) > 0 && !_d.inCourtesyCall(); require( redeemerHoldsTdt || !preTerm, "Only TDT holder can redeem unless deposit is at-term or in COURTESY_CALL" ); bool frtExists = feeRebateTokenHolder(_d) != address(0); bool redeemerHoldsFrt = feeRebateTokenHolder(_d) == _redeemer; uint256 signerFee = signerFeeTbtc(_d); uint256 feeEscrow = calculateRedemptionFeeEscrow( signerFee, preTerm, frtExists, redeemerHoldsTdt, redeemerHoldsFrt ); // Base redemption + fee = total we need to have escrowed to start // redemption. owedToDeposit = calculateBaseRedemptionCharge( lotSizeTbtc(_d), redeemerHoldsTdt ).add(feeEscrow); // Adjust the amount owed to the deposit based on any balance the // deposit already has. uint256 balance = _d.tbtcToken.balanceOf(address(this)); if (owedToDeposit > balance) { owedToDeposit = owedToDeposit.sub(balance); } else { owedToDeposit = 0; } // Pre-term, the FRT rebate is payed out, but if the redeemer holds the // FRT, the amount has already been subtracted from what is owed to the // deposit at this point (by calculateRedemptionFeeEscrow). This allows // the redeemer to simply *not pay* the fee rebate, rather than having // them pay it only to have it immediately returned. if (preTerm && frtExists && !redeemerHoldsFrt) { owedToFrtHolder = signerFee; } // The TDT holder gets any leftover balance. owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); } /// @notice Get the base TBTC amount needed to redeem. /// @param _lotSize The lot size to use for the base redemption charge. /// @param _redeemerHoldsTdt True if the redeemer is the TDT holder. /// @return The amount in TBTC. function calculateBaseRedemptionCharge( uint256 _lotSize, bool _redeemerHoldsTdt ) internal pure returns (uint256){ if (_redeemerHoldsTdt) { return 0; } return _lotSize; } /// @notice Get fees owed for redemption /// @param signerFee The value of the signer fee for fee calculations. /// @param _preTerm True if the Deposit is at-term or in courtesy_call. /// @param _frtExists True if the FRT exists. /// @param _redeemerHoldsTdt True if the the redeemer holds the TDT. /// @param _redeemerHoldsFrt True if the redeemer holds the FRT. /// @return The fees owed in TBTC. function calculateRedemptionFeeEscrow( uint256 signerFee, bool _preTerm, bool _frtExists, bool _redeemerHoldsTdt, bool _redeemerHoldsFrt ) internal pure returns (uint256) { // Escrow the fee rebate so the FRT holder can be repaids, unless the // redeemer holds the FRT, in which case we simply don't require the // rebate from them. bool escrowRequiresFeeRebate = _preTerm && _frtExists && ! _redeemerHoldsFrt; bool escrowRequiresFee = _preTerm || // If the FRT exists at term/courtesy call, the fee is // "required", but should already be escrowed before redemption. _frtExists || // The TDT holder always owes fees if there is no FRT. _redeemerHoldsTdt; uint256 feeEscrow = 0; if (escrowRequiresFee) { feeEscrow += signerFee; } if (escrowRequiresFeeRebate) { feeEscrow += signerFee; } return feeEscrow; } } pragma solidity 0.5.17; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; library DepositFunding { using SafeMath for uint256; using SafeMath for uint64; using BTCUtils for bytes; using BytesLib for bytes; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Deletes state after funding. /// @dev This is called when we go to ACTIVE or setup fails without fraud. function fundingTeardown(DepositUtils.Deposit storage _d) internal { _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; } /// @notice Deletes state after the funding ECDSA fraud process. /// @dev This is only called as we transition to setup failed. function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal { _d.keepAddress = address(0); _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; _d.signingGroupPubkeyX = bytes32(0); _d.signingGroupPubkeyY = bytes32(0); } /// @notice Internally called function to set up a newly created Deposit /// instance. This should not be called by developers, use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev If called directly, the transaction will revert since the call will /// be executed on an already set-up instance. /// @param _d Deposit storage pointer. /// @param _lotSizeSatoshis Lot size in satoshis. function initialize( DepositUtils.Deposit storage _d, uint64 _lotSizeSatoshis ) public { require(_d.tbtcSystem.getAllowNewDeposits(), "New deposits aren't allowed."); require(_d.inStart(), "Deposit setup already requested"); _d.lotSizeSatoshis = _lotSizeSatoshis; _d.keepSetupFee = _d.tbtcSystem.getNewDepositFeeEstimate(); // Note: this is a library, and library functions cannot be marked as // payable. Thus, we disable Solium's check that msg.value can only be // used in a payable function---this restriction actually applies to the // caller of this `initialize` function, Deposit.initializeDeposit. /* solium-disable-next-line value-in-payable */ _d.keepAddress = _d.tbtcSystem.requestNewKeep.value(msg.value)( _lotSizeSatoshis, TBTCConstants.getDepositTerm() ); require(_d.fetchBondAmount() >= _d.keepSetupFee, "Insufficient signer bonds to cover setup fee"); _d.signerFeeDivisor = _d.tbtcSystem.getSignerFeeDivisor(); _d.undercollateralizedThresholdPercent = _d.tbtcSystem.getUndercollateralizedThresholdPercent(); _d.severelyUndercollateralizedThresholdPercent = _d.tbtcSystem.getSeverelyUndercollateralizedThresholdPercent(); _d.initialCollateralizedPercent = _d.tbtcSystem.getInitialCollateralizedPercent(); _d.signingGroupRequestedAt = block.timestamp; _d.setAwaitingSignerSetup(); _d.logCreated(_d.keepAddress); } /// @notice Anyone may notify the contract that signing group setup has timed out. /// @param _d Deposit storage pointer. function notifySignerSetupFailed(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingSignerSetup(), "Not awaiting setup"); require( block.timestamp > _d.signingGroupRequestedAt.add(TBTCConstants.getSigningGroupFormationTimeout()), "Signing group formation timeout not yet elapsed" ); // refund the deposit owner the cost to create a new Deposit at the time the Deposit was opened. uint256 _seized = _d.seizeSignerBonds(); if(_seized >= _d.keepSetupFee){ /* solium-disable-next-line security/no-send */ _d.enableWithdrawal(_d.depositOwner(), _d.keepSetupFee); _d.pushFundsToKeepGroup(_seized.sub(_d.keepSetupFee)); } _d.setFailedSetup(); _d.logSetupFailed(); fundingTeardown(_d); } /// @notice we poll the Keep contract to retrieve our pubkey. /// @dev We store the pubkey as 2 bytestrings, X and Y. /// @param _d Deposit storage pointer. /// @return True if successful, otherwise revert. function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup"); bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey(); require(_publicKey.length == 64, "public key not set or not 64-bytes long"); _d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32(); _d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32(); require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey"); _d.fundingProofTimerStart = block.timestamp; _d.setAwaitingBTCFundingProof(); _d.logRegisteredPubkey( _d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Anyone may notify the contract that the funder has failed to /// prove that they have sent BTC in time. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Reverts if the funding timeout /// has not yet elapsed, or if the deposit is not currently awaiting /// funding proof. /// @param _d Deposit storage pointer. function notifyFundingTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started"); require( block.timestamp > _d.fundingProofTimerStart.add(TBTCConstants.getFundingTimeout()), "Funding timeout has not elapsed." ); _d.setFailedSetup(); _d.logSetupFailed(); _d.closeKeep(); fundingTeardown(_d); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests return of a sent UTXO to `_abortOutputScript`. This can /// be used for example when a UTXO is sent that is the wrong size /// for the lot. Must be called after setup fails for any reason, /// and imposes no requirement or incentive on the signing group to /// return the UTXO. /// @dev This is a self-admitted funder fault, and should only be callable /// by the TDT holder. /// @param _d Deposit storage pointer. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters require( _d.inFailedSetup(), "The deposit has not failed funding" ); _d.logFunderRequestedAbort(_abortOutputScript); } /// @notice Anyone can provide a signature that was not requested to prove fraud during funding. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. /// @return True if successful, otherwise revert. function provideFundingECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( _d.inAwaitingBTCFundingProof(), "Signer fraud during funding flow only available while awaiting funding" ); _d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); _d.logFraudDuringSetup(); // Allow deposit owner to withdraw seized bonds after contract termination. uint256 _seized = _d.seizeSignerBonds(); _d.enableWithdrawal(_d.depositOwner(), _seized); fundingFraudTeardown(_d); _d.setFailedSetup(); _d.logSetupFailed(); } /// @notice Anyone may notify the deposit of a funding proof to activate the deposit. /// This is the happy-path of the funding flow. It means that we have succeeded. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. function provideBTCFundingProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding"); bytes8 _valueBytes; bytes memory _utxoOutpoint; (_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); // Write down the UTXO info and set to active. Congratulations :) _d.utxoValueBytes = _valueBytes; _d.utxoOutpoint = _utxoOutpoint; _d.fundedAt = block.timestamp; bytes32 _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); fundingTeardown(_d); _d.setActive(); _d.logFunded(_txid); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; library DepositRedemption { using SafeMath for uint256; using CheckBitcoinSigs for bytes; using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Pushes signer fee to the Keep group by transferring it to the Keep address. /// @dev Approves the keep contract, then expects it to call transferFrom. function distributeSignerFee(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _d.tbtcToken.approve(_d.keepAddress, _d.signerFeeTbtc()); _keep.distributeERC20Reward(address(_d.tbtcToken), _d.signerFeeTbtc()); } /// @notice Approves digest for signing by a keep. /// @dev Calls given keep to sign the digest. Records a current timestamp /// for given digest. /// @param _digest Digest to approve. function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal { IBondedECDSAKeep(_d.keepAddress).sign(_digest); _d.approvedDigests[_digest] = block.timestamp; } /// @notice Handles TBTC requirements for redemption. /// @dev Burns or transfers depending on term and supply-peg impact. /// Once these transfers complete, the deposit balance should be /// sufficient to pay out signer fees once the redemption transaction /// is proven on the Bitcoin side. function performRedemptionTbtcTransfers(DepositUtils.Deposit storage _d) internal { address tdtHolder = _d.depositOwner(); address frtHolder = _d.feeRebateTokenHolder(); address vendingMachineAddress = _d.vendingMachineAddress; ( uint256 tbtcOwedToDeposit, uint256 tbtcOwedToTdtHolder, uint256 tbtcOwedToFrtHolder ) = _d.calculateRedemptionTbtcAmounts(_d.redeemerAddress, false); if(tbtcOwedToDeposit > 0){ _d.tbtcToken.transferFrom(msg.sender, address(this), tbtcOwedToDeposit); } if(tbtcOwedToTdtHolder > 0){ if(tdtHolder == vendingMachineAddress){ _d.tbtcToken.burn(tbtcOwedToTdtHolder); } else { _d.tbtcToken.transfer(tdtHolder, tbtcOwedToTdtHolder); } } if(tbtcOwedToFrtHolder > 0){ _d.tbtcToken.transfer(frtHolder, tbtcOwedToFrtHolder); } } function _requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _redeemer ) internal { require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state"); bytes memory _output = abi.encodePacked(_outputValueBytes, _redeemerOutputScript); require(_output.extractHash().length > 0, "Output script must be a standard type"); // set redeemerAddress early to enable direct access by other functions _d.redeemerAddress = _redeemer; performRedemptionTbtcTransfers(_d); // Convert the 8-byte LE ints to uint256 uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint(); uint256 _requestedFee = _d.utxoValue().sub(_outputValue); require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low"); require( _requestedFee < _d.utxoValue() / 2, "Initial fee cannot exceed half of the deposit's value" ); // Calculate the sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _outputValueBytes, _redeemerOutputScript); // write all request details _d.redeemerOutputScript = _redeemerOutputScript; _d.initialRedemptionFee = _requestedFee; _d.latestRedemptionFee = _requestedFee; _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( _redeemer, _sighash, _d.utxoValue(), _redeemerOutputScript, _requestedFee, _d.utxoOutpoint); } /// @notice Anyone can request redemption as long as they can. /// approve the TDT transfer to the final recipient. /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// on behalf of _finalRecipient. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters _d.tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); } /// @notice Only TDT holder can request redemption, /// unless Deposit is expired or in COURTESY_CALL. /// @dev The redeemer specifies details about the Bitcoin redemption transaction. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 curve's order. function provideRedemptionSignature( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); // If we're outside of the signature window, we COULD punish signers here // Instead, we consider this a no-harm-no-foul situation. // The signers have not stolen funds. Most likely they've just inconvenienced someone // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // The signature must be valid on the pubkey require( _d.signerPubkey().checkSig( _d.lastRequestedDigest, _v, _r, _s ), "Invalid signature" ); // A signature has been provided, now we wait for fee bump or redemption _d.setAwaitingWithdrawalProof(); _d.logGotRedemptionSignature( _d.lastRequestedDigest, _r, _s); } /// @notice Anyone may notify the contract that a fee bump is needed. /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE. /// @param _d Deposit storage pointer. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public { require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided"); require(block.timestamp >= _d.withdrawalRequestTime.add(TBTCConstants.getIncreaseFeeTimer()), "Fee increase not yet permitted"); uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes); // If the fee bump shrinks the UTXO value below the minimum allowed // value, clamp it to that minimum. Further fee bumps will be disallowed // by checkRelationshipToPrevious. if (_newOutputValue < TBTCConstants.getMinimumUtxoValue()) { _newOutputValue = TBTCConstants.getMinimumUtxoValue(); } _d.latestRedemptionFee = _d.utxoValue().sub(_newOutputValue); // Calculate the next sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _newOutputValueBytes, _d.redeemerOutputScript); // Ratchet the signature and redemption proof timeouts _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); // Go back to waiting for a signature _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( msg.sender, _sighash, _d.utxoValue(), _d.redeemerOutputScript, _d.latestRedemptionFee, _d.utxoOutpoint); } function checkRelationshipToPrevious( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public view returns (uint256 _newOutputValue){ // Check that we're incrementing the fee by exactly the redeemer's initial fee uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes); _newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes); require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step"); // Calculate the previous one so we can check that it really is the previous one bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _previousOutputValueBytes, _d.redeemerOutputScript); require( _d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime, "Provided previous value does not yield previous sighash" ); } /// @notice Anyone may provide a withdrawal proof to prove redemption. /// @dev The signers will be penalized if this is not called. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function provideRedemptionProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters bytes32 _txid; uint256 _fundingOutputValue; require(_d.inRedemption(), "Redemption proof only allowed from redemption flow"); _fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector); _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders); require((_d.utxoValue().sub(_fundingOutputValue)) <= _d.latestRedemptionFee, "Incorrect fee amount"); // Transfer TBTC to signers and close the keep. distributeSignerFee(_d); _d.closeKeep(); _d.distributeFeeRebate(); // We're done yey! _d.setRedeemed(); _d.redemptionTeardown(); _d.logRedeemed(_txid); } /// @notice Check the redemption transaction input and output vector to ensure the transaction spends /// the correct UTXO and sends value to the appropriate public key hash. /// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient. /// It's safe to look at only the first input/output as anything that breaks this can be considered fraud /// and can be caught by ECDSAFraudProof. /// @param _d Deposit storage pointer. /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @return The value sent to the redeemer's public key hash. function redemptionTransactionChecks( DepositUtils.Deposit storage _d, bytes memory _txInputVector, bytes memory _txOutputVector ) public view returns (uint256) { require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1); require( keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint), "Tx spends the wrong UTXO" ); bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1); bytes memory _expectedOutputScript = _d.redeemerOutputScript; require(_output.length - 8 >= _d.redeemerOutputScript.length, "Output script is too short to extract the expected script"); require( keccak256(_output.slice(8, _expectedOutputScript.length)) == keccak256(_expectedOutputScript), "Tx sends value to wrong output script" ); return (uint256(_output.extractValue())); } /// @notice Anyone may notify the contract that the signers have failed to produce a signature. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionSignatureTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getSignatureTimeout()), "Signature timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionProofTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getRedemptionProofTimeout()), "Proof timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } } pragma solidity 0.5.17; library TBTCConstants { // This is intended to make it easy to update system params // During testing swap this out with another constats contract // System Parameters uint256 public constant BENEFICIARY_FEE_DIVISOR = 1000; // 1/1000 = 10 bps = 0.1% = 0.001 uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10; // multiplier to convert satoshi to TBTC token units uint256 public constant DEPOSIT_TERM_LENGTH = 180 * 24 * 60 * 60; // 180 days in seconds uint256 public constant TX_PROOF_DIFFICULTY_FACTOR = 6; // confirmations on the Bitcoin chain // Redemption Flow uint256 public constant REDEMPTION_SIGNATURE_TIMEOUT = 2 * 60 * 60; // seconds uint256 public constant INCREASE_FEE_TIMER = 4 * 60 * 60; // seconds uint256 public constant REDEMPTION_PROOF_TIMEOUT = 6 * 60 * 60; // seconds uint256 public constant MINIMUM_REDEMPTION_FEE = 2000; // satoshi uint256 public constant MINIMUM_UTXO_VALUE = 2000; // satoshi // Funding Flow uint256 public constant FUNDING_PROOF_TIMEOUT = 3 * 60 * 60; // seconds uint256 public constant FORMATION_TIMEOUT = 3 * 60 * 60; // seconds // Liquidation Flow uint256 public constant COURTESY_CALL_DURATION = 6 * 60 * 60; // seconds uint256 public constant AUCTION_DURATION = 24 * 60 * 60; // seconds // Getters for easy access function getBeneficiaryRewardDivisor() external pure returns (uint256) { return BENEFICIARY_FEE_DIVISOR; } function getSatoshiMultiplier() external pure returns (uint256) { return SATOSHI_MULTIPLIER; } function getDepositTerm() external pure returns (uint256) { return DEPOSIT_TERM_LENGTH; } function getTxProofDifficultyFactor() external pure returns (uint256) { return TX_PROOF_DIFFICULTY_FACTOR; } function getSignatureTimeout() external pure returns (uint256) { return REDEMPTION_SIGNATURE_TIMEOUT; } function getIncreaseFeeTimer() external pure returns (uint256) { return INCREASE_FEE_TIMER; } function getRedemptionProofTimeout() external pure returns (uint256) { return REDEMPTION_PROOF_TIMEOUT; } function getMinimumRedemptionFee() external pure returns (uint256) { return MINIMUM_REDEMPTION_FEE; } function getMinimumUtxoValue() external pure returns (uint256) { return MINIMUM_UTXO_VALUE; } function getFundingTimeout() external pure returns (uint256) { return FUNDING_PROOF_TIMEOUT; } function getSigningGroupFormationTimeout() external pure returns (uint256) { return FORMATION_TIMEOUT; } function getCourtesyCallTimeout() external pure returns (uint256) { return COURTESY_CALL_DURATION; } function getAuctionDuration() external pure returns (uint256) { return AUCTION_DURATION; } } pragma solidity 0.5.17; import {DepositLog} from "../DepositLog.sol"; import {DepositUtils} from "./DepositUtils.sol"; library OutsourceDepositLogging { /// @notice Fires a Created event. /// @dev `DepositLog.logCreated` fires a Created event with /// _keepAddress, msg.sender and block.timestamp. /// msg.sender will be the calling Deposit's address. /// @param _keepAddress The address of the associated keep. function logCreated(DepositUtils.Deposit storage _d, address _keepAddress) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCreated(_keepAddress); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _redeemer The ethereum address of the redeemer. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The redeemer or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( DepositUtils.Deposit storage _d, address _redeemer, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedemptionRequested( _redeemer, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest Signed digest. /// @param _r Signature r value. /// @param _s Signature s value. /// @return True if successful, else revert. function logGotRedemptionSignature( DepositUtils.Deposit storage _d, bytes32 _digest, bytes32 _r, bytes32 _s ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logGotRedemptionSignature( _digest, _r, _s ); } /// @notice Fires a RegisteredPubkey event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRegisteredPubkey( DepositUtils.Deposit storage _d, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRegisteredPubkey( _signingGroupPubkeyX, _signingGroupPubkeyY); } /// @notice Fires a SetupFailed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logSetupFailed(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logSetupFailed(); } /// @notice Fires a FunderAbortRequested event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunderRequestedAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunderRequestedAbort(_abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFraudDuringSetup(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFraudDuringSetup(); } /// @notice Fires a Funded event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunded(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunded(_txid); } /// @notice Fires a CourtesyCalled event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logCourtesyCalled(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCourtesyCalled(); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logStartedLiquidation(_wasFraud); } /// @notice Fires a Redeemed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRedeemed(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedeemed(_txid); } /// @notice Fires a Liquidated event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logLiquidated(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logLiquidated(); } /// @notice Fires a ExitedCourtesyCall event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logExitedCourtesyCall(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logExitedCourtesyCall(); } } pragma solidity 0.5.17; import {TBTCDepositToken} from "./system/TBTCDepositToken.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. contract DepositLog { /* Logging philosophy: Every state transition should fire a log That log should have ALL necessary info for off-chain actors Everyone should be able to ENTIRELY rely on log messages */ // `TBTCDepositToken` mints a token for every new Deposit. // If a token exists for a given ID, we know it is a valid Deposit address. TBTCDepositToken tbtcDepositToken; // This event is fired when we init the deposit event Created( address indexed _depositContractAddress, address indexed _keepAddress, uint256 _timestamp ); // This log event contains all info needed to rebuild the redemption tx // We index on request and signers and digest event RedemptionRequested( address indexed _depositContractAddress, address indexed _requester, bytes32 indexed _digest, uint256 _utxoValue, bytes _redeemerOutputScript, uint256 _requestedFee, bytes _outpoint ); // This log event contains all info needed to build a witnes // We index the digest so that we can search events for the other log event GotRedemptionSignature( address indexed _depositContractAddress, bytes32 indexed _digest, bytes32 _r, bytes32 _s, uint256 _timestamp ); // This log is fired when the signing group returns a public key event RegisteredPubkey( address indexed _depositContractAddress, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY, uint256 _timestamp ); // This event is fired when we enter the FAILED_SETUP state for any reason event SetupFailed( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when a funder requests funder abort after // FAILED_SETUP has been reached. Funder abort is a voluntary signer action // to return UTXO(s) that were sent to a signer-controlled wallet despite // the funding proofs having failed. event FunderAbortRequested( address indexed _depositContractAddress, bytes _abortOutputScript ); // This event is fired when we detect an ECDSA fraud before seeing a funding proof event FraudDuringSetup( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we enter the ACTIVE state event Funded( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is called when we enter the COURTESY_CALL state event CourtesyCalled( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we go from COURTESY_CALL to ACTIVE event ExitedCourtesyCall( address indexed _depositContractAddress, uint256 _timestamp ); // This log event is fired when liquidation event StartedLiquidation( address indexed _depositContractAddress, bool _wasFraud, uint256 _timestamp ); // This event is fired when the Redemption SPV proof is validated event Redeemed( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is fired when Liquidation is completed event Liquidated( address indexed _depositContractAddress, uint256 _timestamp ); // // Logging // /// @notice Fires a Created event. /// @dev We append the sender, which is the deposit contract that called. /// @param _keepAddress The address of the associated keep. /// @return True if successful, else revert. function logCreated(address _keepAddress) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Created(msg.sender, _keepAddress, block.timestamp); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _requester The ethereum address of the requester. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The requester or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( address _requester, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RedemptionRequested( msg.sender, _requester, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest signed digest. /// @param _r signature r value. /// @param _s signature s value. function logGotRedemptionSignature(bytes32 _digest, bytes32 _r, bytes32 _s) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit GotRedemptionSignature( msg.sender, _digest, _r, _s, block.timestamp ); } /// @notice Fires a RegisteredPubkey event. /// @dev We append the sender, which is the deposit contract that called. function logRegisteredPubkey( bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RegisteredPubkey( msg.sender, _signingGroupPubkeyX, _signingGroupPubkeyY, block.timestamp ); } /// @notice Fires a SetupFailed event. /// @dev We append the sender, which is the deposit contract that called. function logSetupFailed() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit SetupFailed(msg.sender, block.timestamp); } /// @notice Fires a FunderAbortRequested event. /// @dev We append the sender, which is the deposit contract that called. function logFunderRequestedAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FunderAbortRequested(msg.sender, _abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev We append the sender, which is the deposit contract that called. function logFraudDuringSetup() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FraudDuringSetup(msg.sender, block.timestamp); } /// @notice Fires a Funded event. /// @dev We append the sender, which is the deposit contract that called. function logFunded(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Funded(msg.sender, _txid, block.timestamp); } /// @notice Fires a CourtesyCalled event. /// @dev We append the sender, which is the deposit contract that called. function logCourtesyCalled() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit CourtesyCalled(msg.sender, block.timestamp); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(bool _wasFraud) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit StartedLiquidation(msg.sender, _wasFraud, block.timestamp); } /// @notice Fires a Redeemed event /// @dev We append the sender, which is the deposit contract that called. function logRedeemed(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Redeemed(msg.sender, _txid, block.timestamp); } /// @notice Fires a Liquidated event /// @dev We append the sender, which is the deposit contract that called. function logLiquidated() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Liquidated(msg.sender, block.timestamp); } /// @notice Fires a ExitedCourtesyCall event /// @dev We append the sender, which is the deposit contract that called. function logExitedCourtesyCall() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit ExitedCourtesyCall(msg.sender, block.timestamp); } /// @notice Sets the tbtcDepositToken contract. /// @dev The contract is used by `approvedToLog` to check if the /// caller is a Deposit contract. This should only be called once. /// @param _tbtcDepositTokenAddress The address of the tbtcDepositToken. function setTbtcDepositToken(TBTCDepositToken _tbtcDepositTokenAddress) internal { require( address(tbtcDepositToken) == address(0), "tbtcDepositToken is already set" ); tbtcDepositToken = _tbtcDepositTokenAddress; } // // AUTH // /// @notice Checks if an address is an allowed logger. /// @dev checks tbtcDepositToken to see if the caller represents /// an existing deposit. /// We don't require this, so deposits are not bricked if the system borks. /// @param _caller The address of the calling contract. /// @return True if approved, otherwise false. function approvedToLog(address _caller) public view returns (bool) { return tbtcDepositToken.exists(uint256(_caller)); } } pragma solidity 0.5.17; import {ERC721Metadata} from "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import {DepositFactoryAuthority} from "./DepositFactoryAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title tBTC Deposit Token for tracking deposit ownership /// @notice The tBTC Deposit Token, commonly referenced as the TDT, is an /// ERC721 non-fungible token whose ownership reflects the ownership /// of its corresponding deposit. Each deposit has one TDT, and vice /// versa. Owning a TDT is equivalent to owning its corresponding /// deposit. TDTs can be transferred freely. tBTC's VendingMachine /// contract takes ownership of TDTs and in exchange returns fungible /// TBTC tokens whose value is backed 1-to-1 by the corresponding /// deposit's BTC. /// @dev Currently, TDTs are minted using the uint256 casting of the /// corresponding deposit contract's address. That is, the TDT's id is /// convertible to the deposit's address and vice versa. TDTs are minted /// automatically by the factory during each deposit's initialization. See /// DepositFactory.createNewDeposit() for more info on how the TDT is minted. contract TBTCDepositToken is ERC721Metadata, DepositFactoryAuthority { constructor(address _depositFactoryAddress) ERC721Metadata("tBTC Deposit Token", "TDT") public { initialize(_depositFactoryAddress); } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token /// @param _tokenId uint256 ID of the token to be minted function mint(address _to, uint256 _tokenId) external onlyFactory { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /// @notice Allow another address to spend on the caller's behalf. /// Set allowance for other address and notify. /// Allows `_spender` to transfer the specified TDT /// on your behalf and then ping the contract about it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface below to receive approval notifications. /// @param _spender `ITokenRecipient`-conforming contract authorized to /// operate on the approved token. /// @param _tdtId The TDT they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall( ITokenRecipient _spender, uint256 _tdtId, bytes memory _extraData ) public returns (bool) { // not external to allow bytes memory parameters approve(address(_spender), _tdtId); _spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); return true; } } /* Authored by Satoshi Nakamoto 🤪 */ pragma solidity 0.5.17; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import {ERC20Detailed} from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import {VendingMachineAuthority} from "./VendingMachineAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title TBTC Token. /// @notice This is the TBTC ERC20 contract. /// @dev Tokens can only be minted by the `VendingMachine` contract. contract TBTCToken is ERC20Detailed, ERC20, VendingMachineAuthority { /// @dev Constructor, calls ERC20Detailed constructor to set Token info /// ERC20Detailed(TokenName, TokenSymbol, NumberOfDecimals) constructor(address _VendingMachine) ERC20Detailed("tBTC", "TBTC", 18) VendingMachineAuthority(_VendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints an amount of the token and assigns it to an account. /// Uses the internal _mint function. /// @param _account The account that will receive the created tokens. /// @param _amount The amount of tokens that will be created. function mint(address _account, uint256 _amount) public onlyVendingMachine returns (bool) { // NOTE: this is a public function with unchecked minting. _mint(_account, _amount); return true; } /// @dev Burns an amount of the token from the given account's balance. /// 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 of tokens that will be burnt. function burnFrom(address _account, uint256 _amount) public { _burnFrom(_account, _amount); } /// @dev Destroys `amount` tokens from `msg.sender`, reducing the /// total supply. /// @param _amount The amount of tokens that will be burnt. function burn(uint256 _amount) public { _burn(msg.sender, _amount); } /// @notice Set allowance for other address and notify. /// Allows `_spender` to spend no more than `_value` /// tokens on your behalf and then ping the contract about /// it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface to receive approval notifications. /// @param _spender Address of contract authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. /// @return true if the `_spender` was successfully approved and acted on /// the approval, false (or revert) otherwise. function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes memory _extraData) public returns (bool) { if (approve(address(_spender), _value)) { _spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } return false; } } pragma solidity 0.5.17; /// @title Deposit Factory Authority /// @notice Contract to secure function calls to the Deposit Factory. /// @dev Secured by setting the depositFactory address and using the onlyFactory /// modifier on functions requiring restriction. contract DepositFactoryAuthority { bool internal _initialized = false; address internal _depositFactory; /// @notice Set the address of the System contract on contract /// initialization. /// @dev Since this function is not access-controlled, it should be called /// transactionally with contract instantiation. In cases where a /// regular contract directly inherits from DepositFactoryAuthority, /// that should happen in the constructor. In cases where the inheritor /// is binstead used via a clone factory, the same function that /// creates a new clone should also trigger initialization. function initialize(address _factory) public { require(_factory != address(0), "Factory cannot be the zero address."); require(! _initialized, "Factory can only be initialized once."); _depositFactory = _factory; _initialized = true; } /// @notice Function modifier ensures modified function is only called by set deposit factory. modifier onlyFactory(){ require(_initialized, "Factory initialization must have been called."); require(msg.sender == _depositFactory, "Caller must be depositFactory contract"); _; } } pragma solidity 0.5.17; /// @title TBTC System Authority. /// @notice Contract to secure function calls to the TBTC System contract. /// @dev The `TBTCSystem` contract address is passed as a constructor parameter. contract TBTCSystemAuthority { address internal tbtcSystemAddress; /// @notice Set the address of the System contract on contract initialization. constructor(address _tbtcSystemAddress) public { tbtcSystemAddress = _tbtcSystemAddress; } /// @notice Function modifier ensures modified function is only called by TBTCSystem. modifier onlyTbtcSystem(){ require(msg.sender == tbtcSystemAddress, "Caller must be tbtcSystem contract"); _; } } pragma solidity 0.5.17; /// @title Vending Machine Authority. /// @notice Contract to secure function calls to the Vending Machine. /// @dev Secured by setting the VendingMachine address and using the /// onlyVendingMachine modifier on functions requiring restriction. contract VendingMachineAuthority { address internal VendingMachine; constructor(address _vendingMachine) public { VendingMachine = _vendingMachine; } /// @notice Function modifier ensures modified function caller address is the vending machine. modifier onlyVendingMachine() { require(msg.sender == VendingMachine, "caller must be the vending machine"); _; } } pragma solidity 0.5.17; /// @title Interface of recipient contract for `approveAndCall` pattern. /// Implementors will be able to be used in an `approveAndCall` /// interaction with a supporting contract, such that a token approval /// can call the contract acting on that approval in a single /// transaction. /// /// See the `FundingScript` and `RedemptionScript` contracts as examples. interface ITokenRecipient { /// Typically called from a token contract's `approveAndCall` method, this /// method will receive the original owner of the token (`_from`), the /// transferred `_value` (in the case of an ERC721, the token id), the token /// address (`_token`), and a blob of `_extraData` that is informally /// specified by the implementor of this method as a way to communicate /// additional parameters. /// /// Token calls to `receiveApproval` should revert if `receiveApproval` /// reverts, and reverts should remove the approval. /// /// @param _from The original owner of the token approved for transfer. /// @param _value For an ERC20, the amount approved for transfer; for an /// ERC721, the id of the token approved for transfer. /// @param _token The address of the contract for the token whose transfer /// was approved. /// @param _extraData An additional data blob forwarded unmodified through /// `approveAndCall`, used to allow the token owner to pass /// additional parameters and data to this method. The structure of /// the extra data is informally specified by the implementor of /// this interface. function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import "./VendingMachineAuthority.sol"; /// @title Fee Rebate Token /// @notice The Fee Rebate Token (FRT) is a non fungible token (ERC721) /// the ID of which corresponds to a given deposit address. /// If the corresponding deposit is still active, ownership of this token /// could result in reimbursement of the signer fee paid to open the deposit. /// @dev This token is minted automatically when a TDT (`TBTCDepositToken`) /// is exchanged for TBTC (`TBTCToken`) via the Vending Machine (`VendingMachine`). /// When the Deposit is redeemed, the TDT holder will be reimbursed /// the signer fee if the redeemer is not the TDT holder and Deposit is not /// at-term or in COURTESY_CALL. contract FeeRebateToken is ERC721Metadata, VendingMachineAuthority { constructor(address _vendingMachine) ERC721Metadata("tBTC Fee Rebate Token", "FRT") VendingMachineAuthority(_vendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token. /// @param _tokenId uint256 ID of the token to be minted. function mint(address _to, uint256 _tokenId) external onlyVendingMachine { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title ECDSA Keep /// @notice Contract reflecting an ECDSA keep. contract IBondedECDSAKeep { /// @notice Returns public key of this keep. /// @return Keeps's public key. function getPublicKey() external view returns (bytes memory); /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256); /// @notice Calculates a signature over provided digest by the keep. Note that /// signatures from the keep not explicitly requested by calling `sign` /// will be provable as fraud via `submitSignatureFraud`. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external; /// @notice Distributes ETH reward evenly across keep signer beneficiaries. /// @dev Only the value passed to this function is distributed. function distributeETHReward() external payable; /// @notice Distributes ERC20 reward evenly across keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function. /// This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external; /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// terminated so it will no longer respond to signing requests. Bonds can /// be seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external; /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds() external payable; /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage)`. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external returns (bool _isFraud); /// @notice Closes keep when no longer needed. Releases bonds to the keep /// members. Keep can be closed only when there is no signing in progress or /// requested signing process has timed out. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() external; } pragma solidity ^0.5.10; /** @title ValidateSPV*/ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; import {BTCUtils} from "./BTCUtils.sol"; library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; } function getErrInvalidChain() internal pure returns (uint256) { return ERR_INVALID_CHAIN; } function getErrLowWork() internal pure returns (uint256) { return ERR_LOW_WORK; } /// @notice Validates a tx inclusion in the block /// @dev `index` is not a reliable indicator of location within a block /// @param _txid The txid (LE) /// @param _merkleRoot The merkle root (as in the block header) /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root) /// @param _index The leaf's index in the tree (0-indexed) /// @return true if fully valid, false otherwise function prove( bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint _index ) internal pure returns (bool) { // Shortcut the empty-block case if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) { return true; } bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot); // If the Merkle proof failed, bubble up error return _proof.verifyHash256Merkle(_index); } /// @notice Hashes transaction to get txid /// @dev Supports Legacy and Witness /// @param _version 4-bytes version /// @param _vin Raw bytes length-prefixed input vector /// @param _vout Raw bytes length-prefixed output vector /// @param _locktime 4-byte tx locktime /// @return 32-byte transaction id, little endian function calculateTxId( bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime ) internal pure returns (bytes32) { // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime) return abi.encodePacked(_version, _vin, _vout, _locktime).hash256(); } /// @notice Checks validity of header chain /// @notice Compares the hash of each header to the prevHash in the next header /// @param _headers Raw byte array of header chain /// @return The total accumulated difficulty of the header chain, or an error code function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) { // Check header chain length if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;} // Initialize header start index bytes32 _digest; _totalDifficulty = 0; for (uint256 _start = 0; _start < _headers.length; _start += 80) { // ith header start index and ith header bytes memory _header = _headers.slice(_start, 80); // After the first header, check that headers are in a chain if (_start != 0) { if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;} } // ith header target uint256 _target = _header.extractTarget(); // Require that the header has sufficient work _digest = _header.hash256View(); if(uint256(_digest).reverseUint256() > _target) { return ERR_LOW_WORK; } // Add ith header difficulty to difficulty sum _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty()); } } /// @notice Checks validity of header work /// @param _digest Header digest /// @param _target The target threshold /// @return true if header work is valid, false otherwise function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) { if (_digest == bytes32(0)) {return false;} return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target); } /// @notice Checks validity of header chain /// @dev Compares current header prevHash to previous header's digest /// @param _header The raw bytes header /// @param _prevHeaderDigest The previous header's digest /// @return true if the connect is valid, false otherwise function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) { // Extract prevHash of current header bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32(); // Compare prevHash of current header to previous header's digest if (_prevHash != _prevHeaderDigest) {return false;} return true; } } pragma solidity ^0.5.10; /** @title CheckBitcoinSigs */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {BTCUtils} from "./BTCUtils.sol"; library CheckBitcoinSigs { using BytesLib for bytes; using BTCUtils for bytes; /// @notice Derives an Ethereum Account address from a pubkey /// @dev The address is the last 20 bytes of the keccak256 of the address /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array /// @return The account address function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) { require(_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key."); // keccak hash of uncompressed unprefixed pubkey bytes32 _digest = keccak256(_pubkey); return address(uint256(_digest)); } /// @notice Calculates the p2wpkh output script of a pubkey /// @dev Compresses keys to 33 bytes as required by Bitcoin /// @param _pubkey The public key, compressed or uncompressed /// @return The p2wkph output script function p2wpkhFromPubkey(bytes memory _pubkey) internal pure returns (bytes memory) { bytes memory _compressedPubkey; uint8 _prefix; if (_pubkey.length == 64) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(0, 32)); } else if (_pubkey.length == 65) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(1, 32)); } else { _compressedPubkey = _pubkey; } require(_compressedPubkey.length == 33, "Witness PKH requires compressed keys"); bytes memory _pubkeyHash = _compressedPubkey.hash160(); return abi.encodePacked(hex"0014", _pubkeyHash); } /// @notice checks a signed message's validity under a pubkey /// @dev does this using ecrecover because Ethereum has no soul /// @param _pubkey the public key to check (64 bytes) /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkSig( bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); address _expected = accountFromPubkey(_pubkey); address _actual = ecrecover(_digest, _v, _r, _s); return _actual == _expected; } /// @notice checks a signed message against a bitcoin p2wpkh output script /// @dev does this my verifying the p2wpkh matches an ethereum account /// @param _p2wpkhOutputScript the bitcoin output script /// @param _pubkey the uncompressed, unprefixed public key to check /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkBitcoinSig( bytes memory _p2wpkhOutputScript, bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer? if (!_isExpectedSigner) {return false;} bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s); return _sigResult; } /// @notice checks if a message is the sha256 preimage of a digest /// @dev this is NOT the hash256! this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isSha256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return sha256(_candidate) == _digest; } /// @notice checks if a message is the keccak256 preimage of a digest /// @dev this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isKeccak256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return keccak256(_candidate) == _digest; } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputScript the length-prefixed output script /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhSpendSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes memory _outputScript // lenght-prefixed output script ) internal pure returns (bytes32) { // Fixes elements to easily make a 1-in 1-out sighash digest // Does not support timelocks bytes memory _scriptCode = abi.encodePacked( hex"1976a914", // length, dup, hash160, pkh_length _inputPKH, hex"88ac"); // equal, checksig bytes32 _hashOutputs = abi.encodePacked( _outputValue, // 8-byte LE _outputScript).hash256(); bytes memory _sighashPreimage = abi.encodePacked( hex"01000000", // version _outpoint.hash256(), // hashPrevouts hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000) _outpoint, // outpoint _scriptCode, // p2wpkh script code _inputValue, // value of the input in 8-byte LE hex"00000000", // input nSequence _hashOutputs, // hash of the single output hex"00000000", // nLockTime hex"01000000" // SIGHASH_ALL ); return _sighashPreimage.hash256(); } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhToWpkhSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhSpendSighash( _outpoint, _inputPKH, _inputValue, _outputValue, abi.encodePacked( hex"160014", // wpkh tag _outputPKH) ); } /// @notice Preserved for API compatibility with older version /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function oneInputOneOutputSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH); } } pragma solidity ^0.5.0; 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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } 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. * * > 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.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity ^0.5.0; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity ^0.5.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * 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 * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * 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.5.0; import "./IERC165.sol"; /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See `IERC165.supportsInterface`. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See `IERC165.supportsInterface`. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity ^0.5.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); }
Mints a new token. Reverts if the given token ID already exists. _to The address that will own the minted token _tokenId uint256 ID of the token to be minted
function mint(address _to, uint256 _tokenId) external onlyFactory { _mint(_to, _tokenId); }
7,283,496
// SPDX-License-Identifier: MIT // Using old version, so that images can rollover pragma solidity ^0.5.13; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.3.0/contracts/math/SafeMath.sol"; contract LicenseExample { using SafeMath for uint; mapping(address => uint) public tokenBalance; constructor() public { tokenBalance[msg.sender] = 1; } // uint rolls over function sendToken(address _to, uint _amount) public returns(bool) { tokenBalance[msg.sender] -= _amount; tokenBalance[_to] += _amount; return true; } // using ... for ... // Using SafeMath library on uint // This will pass value of uint variable to first argument of library method // uint_val.add(val1, val2) // In this case, uint_val will be passed over to val1 and // functions will be called accordingly function sendTokenSafe(address _to, uint _amount) public returns(bool) { tokenBalance[msg.sender] = tokenBalance[msg.sender].sub(_amount); tokenBalance[_to] = tokenBalance[_to].add(_amount); return true; } function getMyBalance() public view returns(uint) { return tokenBalance[msg.sender]; } }
using ... for ... Using SafeMath library on uint This will pass value of uint variable to first argument of library method uint_val.add(val1, val2) In this case, uint_val will be passed over to val1 and functions will be called accordingly
function sendTokenSafe(address _to, uint _amount) public returns(bool) { tokenBalance[msg.sender] = tokenBalance[msg.sender].sub(_amount); tokenBalance[_to] = tokenBalance[_to].add(_amount); return true; }
14,058,482
//Address: 0x54c14fcb13772f6c56d09264e8fc3b050a458cdb //Contract name: ApolloSeptemCrowdsale //Balance: 0 Ether //Verification Date: 2/25/2018 //Transacion Count: 21 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface token { function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); function getTotalSupply() public view returns (uint256); } contract ApolloSeptemBaseCrowdsale { using SafeMath for uint256; // The token being sold token public tokenReward; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // token address address public tokenAddress; // amount of raised money in wei uint256 public weiRaised; // a presale limit of 50% from ico tokens to be sold uint256 public constant PRESALE_LIMIT = 90 * (10 ** 6) * (10 ** 18); // a presale limit is set to minimum of 0.1 ether (100 finney) uint256 public constant PRESALE_BONUS_LIMIT = 100 finney; // Presale period (includes holidays) uint public constant PRESALE_PERIOD = 30 days; // Crowdsale first Wave period uint public constant CROWD_WAVE1_PERIOD = 10 days; // Crowdsale second Wave period uint public constant CROWD_WAVE2_PERIOD = 10 days; // Crowdsale third Wave period uint public constant CROWD_WAVE3_PERIOD = 10 days; // Bonus in percentage uint public constant PRESALE_BONUS = 40; uint public constant CROWD_WAVE1_BONUS = 15; uint public constant CROWD_WAVE2_BONUS = 10; uint public constant CROWD_WAVE3_BONUS = 5; uint256 public limitDatePresale; uint256 public limitDateCrowdWave1; uint256 public limitDateCrowdWave2; uint256 public limitDateCrowdWave3; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event ApolloSeptemTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event ApolloSeptemTokenSpecialPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); function ApolloSeptemBaseCrowdsale(address _wallet, address _tokens) public{ require(_wallet != address(0)); tokenAddress = _tokens; tokenReward = token(tokenAddress); wallet = _wallet; } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token to be substracted uint256 tokens = computeTokens(weiAmount); require(isWithinTokenAllocLimit(tokens)); // update state weiRaised = weiRaised.add(weiAmount); // send tokens to beneficiary tokenReward.transfer(beneficiary, tokens); ApolloSeptemTokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } //transfer used for special contribuitions function specialTransfer(address _to, uint _amount) internal returns(bool){ require(_to != address(0)); require(_amount > 0 ); // calculate token to be substracted uint256 tokens = _amount * (10 ** 18); tokenReward.transfer(_to, tokens); ApolloSeptemTokenSpecialPurchase(msg.sender, _to, tokens); return true; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase && !(isWithinPresaleTimeLimit() && msg.value < PRESALE_BONUS_LIMIT); } function isWithinPresaleTimeLimit() internal view returns (bool) { return now <= limitDatePresale; } function isWithinCrowdWave1TimeLimit() internal view returns (bool) { return now <= limitDateCrowdWave1; } function isWithinCrowdWave2TimeLimit() internal view returns (bool) { return now <= limitDateCrowdWave2; } function isWithinCrowdWave3TimeLimit() internal view returns (bool) { return now <= limitDateCrowdWave3; } function isWithinCrodwsaleTimeLimit() internal view returns (bool) { return now <= endTime && now > limitDatePresale; } function isWithinPresaleLimit(uint256 _tokens) internal view returns (bool) { return tokenReward.balanceOf(this).sub(_tokens) >= PRESALE_LIMIT; } function isWithinCrowdsaleLimit(uint256 _tokens) internal view returns (bool) { return tokenReward.balanceOf(this).sub(_tokens) >= 0; } function isWithinTokenAllocLimit(uint256 _tokens) internal view returns (bool) { return (isWithinPresaleTimeLimit() && isWithinPresaleLimit(_tokens)) || (isWithinCrodwsaleTimeLimit() && isWithinCrowdsaleLimit(_tokens)); } function sendAllToOwner(address beneficiary) internal returns(bool){ tokenReward.transfer(beneficiary, tokenReward.balanceOf(this)); return true; } function computeTokens(uint256 weiAmount) internal view returns (uint256) { uint256 appliedBonus = 0; if (isWithinPresaleTimeLimit()) { appliedBonus = PRESALE_BONUS; } else if (isWithinCrowdWave1TimeLimit()) { appliedBonus = CROWD_WAVE1_BONUS; } else if (isWithinCrowdWave2TimeLimit()) { appliedBonus = CROWD_WAVE2_BONUS; } else if (isWithinCrowdWave3TimeLimit()) { appliedBonus = CROWD_WAVE3_BONUS; } // 1 ETH = 4200 APO return weiAmount.mul(42).mul(100 + appliedBonus); } } /** * @title ApolloSeptemCappedCrowdsale * @dev Extension of ApolloSeptemBaseCrowdsale with a max amount of funds raised */ contract ApolloSeptemCappedCrowdsale is ApolloSeptemBaseCrowdsale{ using SafeMath for uint256; // HARD_CAP = 30,000 ether uint256 public constant HARD_CAP = (3 ether)*(10**4); function ApolloSeptemCappedCrowdsale() public {} // overriding ApolloSeptemBaseCrowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= HARD_CAP; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= HARD_CAP; return super.hasEnded() || capReached; } } /** * @title ApolloSeptemCrowdsale * @dev This is ApolloSeptem's crowdsale contract. */ contract ApolloSeptemCrowdsale is ApolloSeptemCappedCrowdsale, Ownable { bool public isFinalized = false; bool public isStarted = false; event ApolloSeptemStarted(); event ApolloSeptemFinalized(); function ApolloSeptemCrowdsale(address _wallet,address _tokensAddress) public ApolloSeptemCappedCrowdsale() ApolloSeptemBaseCrowdsale(_wallet,_tokensAddress) { } /** * @dev Must be called to start the crowdsale. */ function start() onlyOwner public { require(!isStarted); starting(); ApolloSeptemStarted(); isStarted = true; } function starting() internal { startTime = now; limitDatePresale = startTime + PRESALE_PERIOD; limitDateCrowdWave1 = limitDatePresale + CROWD_WAVE1_PERIOD; limitDateCrowdWave2 = limitDateCrowdWave1 + CROWD_WAVE2_PERIOD; limitDateCrowdWave3 = limitDateCrowdWave2 + CROWD_WAVE3_PERIOD; endTime = limitDateCrowdWave3; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); ApolloSeptemFinalized(); isFinalized = true; } /** * @dev Must be called only in special cases */ function apolloSpecialTransfer(address _beneficiary, uint _amount) onlyOwner public { specialTransfer(_beneficiary, _amount); } /** *@dev Must be called after the crowdsale ends, to send the remaining tokens back to owner **/ function sendRemaningBalanceToOwner(address _tokenOwner) onlyOwner public { require(!isFinalized); require(_tokenOwner != address(0)); sendAllToOwner(_tokenOwner); } }
low level token purchase function calculate token to be substracted update state send tokens to beneficiary
function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = computeTokens(weiAmount); require(isWithinTokenAllocLimit(tokens)); weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); ApolloSeptemTokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); }
12,877,792
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "./CvcOntologyInterface.sol"; import "../upgradeability/Initializable.sol"; import "../upgradeability/Ownable.sol"; import "../upgradeability/EternalStorage.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CvcOntology * @dev This contract holds the list of all recognized Credential Items available for sale. */ contract CvcOntology is EternalStorage, Initializable, Ownable, CvcOntologyInterface { using SafeMath for uint256; /** Data structures and storage layout: struct CredentialItem { string type; // "claim" or "credential" string name; // e.g. "proofOfIdentity" string version; // e.g. "v1.2" string reference; // e.g. "https://example.com/credential-proofOfIdentity-v1_2.json" string referenceType; // e.g. "JSON-LD-Context" bytes32 referenceHash; // e.g. "0x2cd9bf92c5e20b1b410f5ace94d963a96e89156fbe65b70365e8596b37f1f165" bool deprecated; // e.g. false } uint256 recordsCount; bytes32[] recordsIds; mapping(bytes32 => CredentialItem) records; **/ /** * Constructor to initialize with some default values */ constructor() public { initialize(msg.sender); } /** * @dev Adds new Credential Item to the registry. * @param _recordType Credential Item type * @param _recordName Credential Item name * @param _recordVersion Credential Item version * @param _reference Credential Item reference URL * @param _referenceType Credential Item reference type * @param _referenceHash Credential Item reference hash */ function add( string _recordType, string _recordName, string _recordVersion, string _reference, string _referenceType, bytes32 _referenceHash ) external onlyInitialized onlyOwner { require(bytes(_recordType).length > 0, "Empty credential item type"); require(bytes(_recordName).length > 0, "Empty credential item name"); require(bytes(_recordVersion).length > 0, "Empty credential item version"); require(bytes(_reference).length > 0, "Empty credential item reference"); require(bytes(_referenceType).length > 0, "Empty credential item type"); require(_referenceHash != 0x0, "Empty credential item reference hash"); bytes32 id = calculateId(_recordType, _recordName, _recordVersion); require(getReferenceHash(id) == 0x0, "Credential item record already exists"); setType(id, _recordType); setName(id, _recordName); setVersion(id, _recordVersion); setReference(id, _reference); setReferenceType(id, _referenceType); setReferenceHash(id, _referenceHash); setRecordId(getCount(), id); incrementCount(); } /** * @dev Contract initialization method. * @param _owner Contract owner address */ function initialize(address _owner) public initializes { setOwner(_owner); } /** * @dev Deprecates single Credential Item of specific type, name and version. * @param _type Record type to deprecate * @param _name Record name to deprecate * @param _version Record version to deprecate */ function deprecate(string _type, string _name, string _version) public onlyInitialized onlyOwner { deprecateById(calculateId(_type, _name, _version)); } /** * @dev Deprecates single Credential Item by ontology record ID. * @param _id Ontology record ID */ function deprecateById(bytes32 _id) public onlyInitialized onlyOwner { require(getReferenceHash(_id) != 0x0, "Cannot deprecate unknown credential item"); require(getDeprecated(_id) == false, "Credential item is already deprecated"); setDeprecated(_id); } /** * @dev Returns single Credential Item data up by ontology record ID. * @param _id Ontology record ID to search by * @return id Ontology record ID * @return recordType Credential Item type * @return recordName Credential Item name * @return recordVersion Credential Item version * @return reference Credential Item reference URL * @return referenceType Credential Item reference type * @return referenceHash Credential Item reference hash * @return deprecated Credential Item type deprecation flag */ function getById( bytes32 _id ) public view onlyInitialized returns ( bytes32 id, string recordType, string recordName, string recordVersion, string reference, string referenceType, bytes32 referenceHash, bool deprecated ) { referenceHash = getReferenceHash(_id); if (referenceHash != 0x0) { recordType = getType(_id); recordName = getName(_id); recordVersion = getVersion(_id); reference = getReference(_id); referenceType = getReferenceType(_id); deprecated = getDeprecated(_id); id = _id; } } /** * @dev Returns single Credential Item of specific type, name and version. * @param _type Credential Item type * @param _name Credential Item name * @param _version Credential Item version * @return id Ontology record ID * @return recordType Credential Item type * @return recordName Credential Item name * @return recordVersion Credential Item version * @return reference Credential Item reference URL * @return referenceType Credential Item reference type * @return referenceHash Credential Item reference hash * @return deprecated Credential Item type deprecation flag */ function getByTypeNameVersion( string _type, string _name, string _version ) public view onlyInitialized returns ( bytes32 id, string recordType, string recordName, string recordVersion, string reference, string referenceType, bytes32 referenceHash, bool deprecated ) { return getById(calculateId(_type, _name, _version)); } /** * @dev Returns all records. Currently is supported only from internal calls. * @return CredentialItem[] */ function getAll() public view onlyInitialized returns (CredentialItem[]) { uint256 count = getCount(); bytes32 id; CredentialItem[] memory records = new CredentialItem[](count); for (uint256 i = 0; i < count; i++) { id = getRecordId(i); records[i] = CredentialItem( id, getType(id), getName(id), getVersion(id), getReference(id), getReferenceType(id), getReferenceHash(id) ); } return records; } /** * @dev Returns all ontology record IDs. * Could be used from web3.js to retrieve the list of all records. * @return bytes32[] */ function getAllIds() public view onlyInitialized returns(bytes32[]) { uint256 count = getCount(); bytes32[] memory ids = new bytes32[](count); for (uint256 i = 0; i < count; i++) { ids[i] = getRecordId(i); } return ids; } /** * @dev Returns the number of registered ontology records. * @return uint256 */ function getCount() internal view returns (uint256) { // return recordsCount; return uintStorage[keccak256("records.count")]; } /** * @dev Increments total record count. */ function incrementCount() internal { // recordsCount = getCount().add(1); uintStorage[keccak256("records.count")] = getCount().add(1); } /** * @dev Returns the ontology record ID by numeric index. * @return bytes32 */ function getRecordId(uint256 _index) internal view returns (bytes32) { // return recordsIds[_index]; return bytes32Storage[keccak256(abi.encodePacked("records.ids.", _index))]; } /** * @dev Saves ontology record ID against the index. * @param _index Numeric index. * @param _id Ontology record ID. */ function setRecordId(uint256 _index, bytes32 _id) internal { // recordsIds[_index] = _id; bytes32Storage[keccak256(abi.encodePacked("records.ids.", _index))] = _id; } /** * @dev Returns the Credential Item type. * @return string */ function getType(bytes32 _id) internal view returns (string) { // return records[_id].type; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))]; } /** * @dev Saves Credential Item type. * @param _id Ontology record ID. * @param _type Credential Item type. */ function setType(bytes32 _id, string _type) internal { // records[_id].type = _type; stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))] = _type; } /** * @dev Returns the Credential Item name. * @return string */ function getName(bytes32 _id) internal view returns (string) { // records[_id].name; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))]; } /** * @dev Saves Credential Item name. * @param _id Ontology record ID. * @param _name Credential Item name. */ function setName(bytes32 _id, string _name) internal { // records[_id].name = _name; stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))] = _name; } /** * @dev Returns the Credential Item version. * @return string */ function getVersion(bytes32 _id) internal view returns (string) { // return records[_id].version; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".version"))]; } /** * @dev Saves Credential Item version. * @param _id Ontology record ID. * @param _version Credential Item version. */ function setVersion(bytes32 _id, string _version) internal { // records[_id].version = _version; stringStorage[keccak256(abi.encodePacked("records.", _id, ".version"))] = _version; } /** * @dev Returns the Credential Item reference URL. * @return string */ function getReference(bytes32 _id) internal view returns (string) { // return records[_id].reference; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))]; } /** * @dev Saves Credential Item reference URL. * @param _id Ontology record ID. * @param _reference Reference value. */ function setReference(bytes32 _id, string _reference) internal { // records[_id].reference = _reference; stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))] = _reference; } /** * @dev Returns the Credential Item reference type value. * @return string */ function getReferenceType(bytes32 _id) internal view returns (string) { // return records[_id].referenceType; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".referenceType"))]; } /** * @dev Saves Credential Item reference type. * @param _id Ontology record ID. * @param _referenceType Reference type. */ function setReferenceType(bytes32 _id, string _referenceType) internal { // records[_id].referenceType = _referenceType; stringStorage[keccak256(abi.encodePacked("records.", _id, ".referenceType"))] = _referenceType; } /** * @dev Returns the Credential Item reference hash value. * @return bytes32 */ function getReferenceHash(bytes32 _id) internal view returns (bytes32) { // return records[_id].referenceHash; return bytes32Storage[keccak256(abi.encodePacked("records.", _id, ".referenceHash"))]; } /** * @dev Saves Credential Item reference hash. * @param _id Ontology record ID. * @param _referenceHash Reference hash. */ function setReferenceHash(bytes32 _id, bytes32 _referenceHash) internal { // records[_id].referenceHash = _referenceHash; bytes32Storage[keccak256(abi.encodePacked("records.", _id, ".referenceHash"))] = _referenceHash; } /** * @dev Returns the Credential Item deprecation flag value. * @return bool */ function getDeprecated(bytes32 _id) internal view returns (bool) { // return records[_id].deprecated; return boolStorage[keccak256(abi.encodePacked("records.", _id, ".deprecated"))]; } /** * @dev Sets Credential Item deprecation flag value. * @param _id Ontology record ID. */ function setDeprecated(bytes32 _id) internal { // records[_id].deprecated = true; boolStorage[keccak256(abi.encodePacked("records.", _id, ".deprecated"))] = true; } /** * @dev Calculates ontology record ID. * @param _type Credential Item type. * @param _name Credential Item name. * @param _version Credential Item version. */ function calculateId(string _type, string _name, string _version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_type, ".", _name, ".", _version)); } }
Increments total record count./ recordsCount = getCount().add(1);
function incrementCount() internal { uintStorage[keccak256("records.count")] = getCount().add(1); }
14,016,861
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import './ExchangeStructs.sol'; /// @title Exchange /// @author Karim Helmy // Primary contract: Describes functions of exchange contract Exchange is ExchangeStructs { // TODO: Make all operations safe using SafeMath for uint; // SECTION: Declaring/initializing variables address public owner = msg.sender; uint public PRECISION = 10 ** 18; // separate out the open balance (includes unclosed fees, gas fees), // which will be distributed between miners, the exchange, and traders, // from closed balance, which belongs to the exchange uint public openBalance = 0; Parameters public params; // separate chapters for different currency pairs // that's why they're 2D /* * Web3 can't properly handle structs. * Ethers.js can only handle them under experimental version. * Therefore, the old orderBook and adressBook pattern won't work. * ¯\_(ツ)_/¯ */ // separate chapters for different currency pairs // that's why they're 2D mapping (uint => bool[]) public buyBook; mapping (uint => uint[]) public volBook; mapping (uint => uint[]) public minVolBook; mapping (uint => uint[]) public limitBook; mapping (uint => address[]) public ethAddressBook; mapping (uint => bytes32[]) public firstAddressBook; mapping (uint => bytes32[]) public secondAddressBook; // Fixed fees per unit, rather than using dynamic exchange rate // Different fees for buy/sell // can be done with mapping (uint => mapping (bool => uint)) // Allows us to use multiple currencies (not just Ether trading pairs) mapping (uint => mapping (bool => uint)) closureFees; mapping (uint => mapping (bool => uint)) cancelFees; // KYC whitelists mapping (address => bool) minerWhitelist; mapping (address => bool) traderWhitelist; // Numbers of orders that have been closed are kept here uint[] numsCleared; // SECTION: Constructor and helpers // Constructor for contract function Exchange(uint closureFeeBuy0, uint closureFeeSell0, uint cancelFeeBuy0, uint cancelFeeSell0, uint cleanSize, uint minerShare, bytes32 difficulty, bool minerKYC, bool traderKYC) public { // Initialize parameters books setParams(cleanSize, minerShare, difficulty, minerKYC, traderKYC); // Initialize order books addChapter(0, closureFeeBuy0, closureFeeSell0, cancelFeeBuy0, cancelFeeSell0); return; } // SECTION: Permissions // Modified: http://solidity.readthedocs.io/en/v0.3.1/common-patterns.html modifier onlyBy(address _account) { require(msg.sender == _account); _; } modifier minerWhitelisted(address _account) { require(minerWhitelist[msg.sender] || ! params.minerKYC); _; } modifier traderWhitelisted(address _account) { require(traderWhitelist[msg.sender] || ! params.traderKYC); _; } function changeOwner(address _newOwner) public onlyBy(owner) { owner = _newOwner; } function addToMinerWhitelist(address newAddress) public onlyBy(owner) { minerWhitelist[newAddress] = true; } function addToTraderWhitelist(address newAddress) public onlyBy(owner) { traderWhitelist[newAddress] = true; } /* * Initializes order book and address book for chapter * Only used in constructor * Pushes "genesis order" to chapter * ONLY USE FOR MOST RECENT CHAPTER + 1 */ function addChapter(uint chapter, uint closureFeeBuy, uint closureFeeSell, uint cancelFeeBuy, uint cancelFeeSell) public onlyBy(owner) { buyBook[chapter].push(false); volBook[chapter].push(0); minVolBook[chapter].push(0); limitBook[chapter].push(0); ethAddressBook[chapter].push(address(0)); firstAddressBook[chapter].push(bytes32(0)); secondAddressBook[chapter].push(bytes32(0)); // Initialize numsCleared[chapter] as zero numsCleared.push(0); closureFees[chapter][true] = closureFeeBuy; closureFees[chapter][false] = closureFeeSell; cancelFees[chapter][true] = cancelFeeBuy; cancelFees[chapter][false] = cancelFeeSell; } // Init the params struct, which contains the bulk of exchange's parameters // Only used in constructor function setParams(uint cleanSize, uint minerShare, bytes32 difficulty, bool minerKYC, bool traderKYC) internal { params.cleanSize = cleanSize; params.minerShare = minerShare; params.difficulty = difficulty; params.minerKYC = minerKYC; params.traderKYC = traderKYC; } // SECTION: Getters // Get chapter from order book function getOrderChapter(uint chapter) external view returns(bool[] buyChapter, uint[] volChapter, uint[] minVolChapter, uint[] limitChapter) { return(buyBook[chapter], volBook[chapter], minVolBook[chapter], limitBook[chapter]); } /* * Wish I could've bundled these. * For some reason, get a bug when firstAddressChapter and secondAddressChapter are together. * Suspect it has something to do with returning dynamic arrays of fixed size arrays */ // Get chapter from ethAddressBook function getETHAddressChapter(uint chapter) external view returns(address[] ethAddressChapter) { return(ethAddressBook[chapter]); } // Get chapter from firstAddressBook function getFirstAddressChapter(uint chapter) external view returns(bytes32[] firstAddressChapter) { return(firstAddressBook[chapter]); } // Get chapter from secondAddressBook function getSecondAddressChapter(uint chapter) external view returns(bytes32[] secondAddressChapter) { return(secondAddressBook[chapter]); } // SECTION: Core functionality // Checks edge cases for match verification function checkMatchEdges(uint chapter, uint index1, uint index2) private view returns(bool passes) { // valid indices require(index1 < buyBook[chapter].length); require(index2 < buyBook[chapter].length); //One buy order and one sell order require(buyBook[chapter][index1] != buyBook[chapter][index2]); //Non-empty order require(volBook[chapter][index1] != 0); require(volBook[chapter][index2] != 0); // All edge cases work! return true; } // verifies that match is valid function calcRateAndVol(uint chapter, uint index1, uint index2) public view returns (uint mimRate, uint alphaVol) { // check edge cases if (! checkMatchEdges(chapter, index1, index2)) { return (0,0); } // which order is buying and selling ETH? // buy-sell copy1 uint buyIndex; uint sellIndex; if (buyBook[chapter][index1]) { buyIndex = index1; sellIndex = index2; } else{ buyIndex = index2; sellIndex = index1; } // shorthand for buy and sell orders Order memory buyOrder = Order(true, volBook[chapter][buyIndex], minVolBook[chapter][buyIndex], limitBook[chapter][buyIndex]); Order memory sellOrder = Order(false, volBook[chapter][sellIndex], minVolBook[chapter][sellIndex], limitBook[chapter][sellIndex]); // Non-contradictory limits if (buyOrder.limit < sellOrder.limit) { return (0, 0); } // Meet in middle rate // mimRate mimRate = (buyOrder.limit + sellOrder.limit) / 2; // Volumes comparable if (buyOrder.volume * PRECISION > sellOrder.volume * mimRate) { if (buyOrder.minVolume * PRECISION > sellOrder.volume * mimRate) { return (0, 0); } return (mimRate, sellOrder.volume * mimRate); } if (sellOrder.volume * mimRate > buyOrder.volume * PRECISION ) { if (sellOrder.minVolume * mimRate > buyOrder.volume * PRECISION) { return (0, 0); } } return (mimRate, buyOrder.volume); } // Clears closed trade, reenters into order book if incomplete function clearTrade(uint chapter, uint index1, uint index2, uint mimRate, uint alphaVol) private { // which order is buying and selling ETH? // buy-sell copy1 uint buyIndex; uint sellIndex; if (buyBook[chapter][index1]) { buyIndex = index1; sellIndex = index2; } else{ buyIndex = index2; sellIndex = index1; } clearOrder(chapter, buyIndex, mimRate, alphaVol, true); clearOrder(chapter, sellIndex, mimRate, alphaVol, false); } function clearOrder(uint chapter, uint index, uint mimRate, uint alphaVol, bool buyAlpha) private { if (buyAlpha) { if (volBook[chapter][index] == alphaVol) { numsCleared[chapter] += 1; } if (minVolBook[chapter][index] < alphaVol) { minVolBook[chapter][index] = 0; } else{ minVolBook[chapter][index] -= alphaVol; } volBook[chapter][index] -= alphaVol; } else{ if (volBook[chapter][index] == (alphaVol * mimRate / PRECISION)) { numsCleared[chapter] += 1; } if (minVolBook[chapter][index] < (alphaVol * mimRate / PRECISION)) { minVolBook[chapter][index] = 0; } else{ minVolBook[chapter][index] -= (alphaVol * mimRate / PRECISION); } volBook[chapter][index] -= alphaVol * mimRate / PRECISION; } } // Adds trade to log, for traders to note // http://solidity.readthedocs.io/en/latest/contracts.html?highlight=events#events function alertTraders(uint chapter, uint index1, uint index2, uint mimRate, uint alphaVol) private { ethAddressBook[chapter][index1].call.gas(0).value(0)( TradeInfo( ethAddressBook[chapter][index2], // counterEthAddress, firstAddressBook[chapter][index2], // counterFirstAddress, secondAddressBook[chapter][index2], // counterSecondAddress, mimRate, alphaVol ) ); ethAddressBook[chapter][index2].call.gas(0).value(0)( TradeInfo( ethAddressBook[chapter][index1], // counterEthAddress, firstAddressBook[chapter][index1], // counterFirstAddress, secondAddressBook[chapter][index1], // counterSecondAddress, mimRate, alphaVol ) ); } // Move balance from open to closed function clearBalance(uint chapter, uint alphaVol, uint buyLimit) private { openBalance -= (closureFees[chapter][false] * alphaVol) / PRECISION; openBalance -= (closureFees[chapter][true] * alphaVol * buyLimit) / (PRECISION * PRECISION); } // Clean chapter (called when size reaches size to clean) function cleanChapter(uint chapter) private returns(bool cleaned) { // Clean chapter only if size is appropriate if (numsCleared[chapter] < params.cleanSize) { return false; } // For all orders // If it's a cleared order: // Replace it with the next one, and clear the next one for (uint i = 1; i < buyBook[chapter].length; i++) { if (volBook[chapter][i] == 0) { if (i < buyBook[chapter].length - 1) { buyBook[chapter][i] = buyBook[chapter][i+1]; volBook[chapter][i] = volBook[chapter][i+1]; minVolBook[chapter][i] = minVolBook[chapter][i+1]; limitBook[chapter][i] = limitBook[chapter][i+1]; ethAddressBook[chapter][i] = ethAddressBook[chapter][i+1]; firstAddressBook[chapter][i] = firstAddressBook[chapter][i+1]; secondAddressBook[chapter][i] = secondAddressBook[chapter][i+1]; delete buyBook[chapter][i+1]; delete volBook[chapter][i+1]; delete minVolBook[chapter][i+1]; delete limitBook[chapter][i+1]; delete ethAddressBook[chapter][i+1]; delete firstAddressBook[chapter][i+1]; delete secondAddressBook[chapter][i+1]; } } } buyBook[chapter].length = buyBook[chapter].length - numsCleared[chapter]; volBook[chapter].length = volBook[chapter].length - numsCleared[chapter]; minVolBook[chapter].length = minVolBook[chapter].length - numsCleared[chapter]; limitBook[chapter].length = limitBook[chapter].length - numsCleared[chapter]; ethAddressBook[chapter].length = ethAddressBook[chapter].length - numsCleared[chapter]; firstAddressBook[chapter].length = firstAddressBook[chapter].length - numsCleared[chapter]; secondAddressBook[chapter].length = secondAddressBook[chapter].length - numsCleared[chapter]; numsCleared[chapter] = 0; return true; } // Checks if POW (nonce) is valid // Performs nonce verification (keccak256) // Helper for giveMatch function isValidPOW(address depositAddress, uint chapter, uint index1, uint index2, uint nonce) private view returns(bool isValid) { if (params.difficulty < keccak256(depositAddress, chapter, index1, index2, nonce)) { return false; } return true; } // Function to pay the miner what's due function payMiner(uint chapter, address depositAddress, uint alphaVol) private { // Calculate the miner's payment uint minerPayment = ((params.minerShare * closureFees[chapter][true] * alphaVol) / (PRECISION * PRECISION)); // Pay the miner depositAddress.transfer(minerPayment); } // Miners suggest matches with this function // Wrapper for calcRateAndVol and isValidPOW, performs other required functions function giveMatch(address depositAddress, uint chapter, uint index1, uint index2, uint nonce) public minerWhitelisted(msg.sender) returns(bool isValid) { // Validate nonce require(isValidPOW(depositAddress, chapter, index1, index2, nonce)); var (mimRate, alphaVol) = calcRateAndVol(chapter, index1, index2); require(alphaVol > 0); // which order is buying and selling ETH? // buy-sell copy1 uint buyIndex; uint sellIndex; if (buyBook[chapter][index1]) { buyIndex = index1; sellIndex = index2; } else{ buyIndex = index2; sellIndex = index1; } payMiner(chapter, depositAddress, alphaVol); clearBalance(chapter, alphaVol, limitBook[chapter][buyIndex]); alertTraders(chapter, buyIndex, sellIndex, mimRate, alphaVol); clearTrade(chapter, index1, index2, mimRate, alphaVol); cleanChapter(chapter); return true; } // Checks whether user has paid enough with the order that was placed function paidEnough(bool buyAlpha, uint value, uint volume, uint limit, uint chapter) private returns(bool accepted) { if (buyAlpha) { require(limit * value >= volume * closureFees[chapter][buyAlpha]); openBalance += volume * closureFees[chapter][buyAlpha] * limit / (PRECISION * PRECISION); msg.sender.transfer(value - (volume * closureFees[chapter][buyAlpha] * limit / (PRECISION * PRECISION))); } else{ require(value >= volume * closureFees[chapter][buyAlpha] / PRECISION); openBalance += volume * closureFees[chapter][buyAlpha] / PRECISION; msg.sender.transfer(value - (volume * closureFees[chapter][buyAlpha] / PRECISION)); } return true; } function placeTakeBuy(uint volume, address ethAddress, bytes32 firstAddress, bytes32 otherAddress, uint chapter, uint index1) internal returns(uint alphaVol) { require(volume >= minVolBook[chapter][index1] * limitBook[chapter][index1] / PRECISION); require(volume <= volBook[chapter][index1] * limitBook[chapter][index1] / PRECISION); alphaVol = volume; ethAddress.call.gas(0).value(0)( TradeInfo( ethAddressBook[chapter][index1], // counterEthAddress, firstAddressBook[chapter][index1], // counterFirstAddress, secondAddressBook[chapter][index1], // counterSecondAddress, limitBook[chapter][index1], alphaVol ) ); ethAddressBook[chapter][index1].call.gas(0).value(0)( TradeInfo( ethAddress, // counterEthAddress, firstAddress, // counterFirstAddress, otherAddress, // counterSecondAddress, limitBook[chapter][index1], alphaVol ) ); return(alphaVol); } function placeTakeSell(uint volume, address ethAddress, bytes32 firstAddress, bytes32 otherAddress, uint chapter, uint index1) internal returns(uint alphaVol) { alphaVol = volume * limitBook[chapter][index1] / PRECISION; require(alphaVol >= minVolBook[chapter][index1]); require(alphaVol <= volBook[chapter][index1]); ethAddressBook[chapter][index1].call.gas(0).value(0)( TradeInfo( ethAddress, // counterEthAddress, firstAddress, // counterFirstAddress, otherAddress, // counterSecondAddress, limitBook[chapter][index1], alphaVol ) ); ethAddress.call.gas(0).value(0)( TradeInfo( ethAddressBook[chapter][index1], // counterEthAddress, firstAddressBook[chapter][index1], // counterFirstAddress, secondAddressBook[chapter][index1], // counterSecondAddress, limitBook[chapter][index1], alphaVol ) ); return(alphaVol); } // Place market taker orders: choose an index and match with it function placeTakeOrder(bool buyAlpha, uint volume, address ethAddress, bytes32 firstAddress, bytes32 otherAddress, uint chapter, uint index1, uint nonce) public payable traderWhitelisted(msg.sender) returns(bool accepted) { require(index1 < buyBook[chapter].length); //One buy order and one sell order require(buyAlpha != buyBook[chapter][index1]); //Non-empty order require(volBook[chapter][index1] != 0); require(volume > 0); require(isValidPOW(ethAddress, chapter, 0, index1, nonce)); require(paidEnough(buyAlpha, msg.value, volume, limitBook[chapter][index1], chapter)); uint alphaVol; if (buyAlpha) { alphaVol = placeTakeBuy(volume, ethAddress, firstAddress, otherAddress, chapter, index1); } else { alphaVol = placeTakeSell(volume, ethAddress, firstAddress, otherAddress, chapter, index1); } clearBalance(alphaVol, limitBook[chapter][index1], limitBook[chapter][index1]); clearOrder(chapter, index1, limitBook[chapter][index1], alphaVol, ! buyAlpha); cleanChapter(chapter); return true; } // Allows traders to place (limit) orders function placeOrder(bool buyAlpha, uint volume, uint minVolume, uint limit, address ethAddress, bytes32 firstAddress, bytes32 otherAddress, uint chapter) public payable traderWhitelisted(msg.sender) returns(bool accepted) { require(volume > 0); require(minVolume > 0); require(volume >= minVolume); require(limit > 0); require(paidEnough(buyAlpha, msg.value, volume, limit, chapter)); require(buyBook[chapter].length > 0); buyBook[chapter].push(buyAlpha); volBook[chapter].push(volume); minVolBook[chapter].push(minVolume); limitBook[chapter].push(limit); ethAddressBook[chapter].push(ethAddress); firstAddressBook[chapter].push(firstAddress); secondAddressBook[chapter].push(otherAddress); return true; } // Allows traders to cancel orders function cancelOrder(uint chapter, uint index) public returns(bool accepted) { require(index < buyBook[chapter].length); // Can't cancel other people's orders require(msg.sender == ethAddressBook[chapter][index]); uint limit = limitBook[chapter][index]; uint volume = volBook[chapter][index]; bool buyAlpha = buyBook[chapter][index]; // Refund according to alpha transaction volume if (buyBook[chapter][index]) { msg.sender.transfer(volume * (closureFees[chapter][buyAlpha] - cancelFees[chapter][buyAlpha]) / limit); } else{ msg.sender.transfer(volume * (closureFees[chapter][buyAlpha] - cancelFees[chapter][buyAlpha]) / limit); } delete buyBook[chapter][index]; delete volBook[chapter][index]; delete minVolBook[chapter][index]; delete limitBook[chapter][index]; delete ethAddressBook[chapter][index]; delete firstAddressBook[chapter][index]; delete secondAddressBook[chapter][index]; numsCleared[chapter] += 1; cleanChapter(chapter); return true; } }
Wish I could've bundled these. For some reason, get a bug when firstAddressChapter and secondAddressChapter are together. Suspect it has something to do with returning dynamic arrays of fixed size arrays/ Get chapter from ethAddressBook
function getETHAddressChapter(uint chapter) external view returns(address[] ethAddressChapter) { return(ethAddressBook[chapter]); }
13,078,197
pragma solidity ^0.4.19; /* Adapted from strings.sol created by Nick Johnson <[email protected]> * Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> */ library strings { struct slice { uint _len; uint _ptr; } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal pure returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal pure returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } } /* Helper String Functions for Game Manager Contract * @title String Healpers * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract StringHelpers { using strings for *; function stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) constant internal returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function implementsERC721() public pure returns (bool); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } contract CSCPreSaleItemBase is ERC721, OperationalControl, StringHelpers { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CSCPreSaleFactory"; string public constant SYMBOL = "CSCPF"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev CSC Pre Sale Struct, having details of the collectible struct CSCPreSaleItem { /// @dev sequence ID i..e Local Index uint256 sequenceId; /// @dev name of the collectible stored in bytes bytes32 collectibleName; /// @dev Collectible Type uint256 collectibleType; /// @dev Collectible Class uint256 collectibleClass; /// @dev owner address address owner; /// @dev redeemed flag (to help whether it got redeemed or not) bool isRedeemed; } /// @dev array of CSCPreSaleItem type holding information on the Collectibles Created CSCPreSaleItem[] allPreSaleItems; /// @dev Max Count for preSaleItem type -> preSaleItem class -> max. limit mapping(uint256 => mapping(uint256 => uint256)) public preSaleItemTypeToClassToMaxLimit; /// @dev Map from preSaleItem type -> preSaleItem class -> max. limit set (bool) mapping(uint256 => mapping(uint256 => bool)) public preSaleItemTypeToClassToMaxLimitSet; /// @dev Map from preSaleItem type -> preSaleItem class -> Name (string / bytes32) mapping(uint256 => mapping(uint256 => bytes32)) public preSaleItemTypeToClassToName; // @dev mapping which holds all the possible addresses which are allowed to interact with the contract mapping (address => bool) approvedAddressList; // @dev mapping holds the preSaleItem -> owner details mapping (uint256 => address) public preSaleItemIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from preSaleItem to an address that has been approved to call /// transferFrom(). Each Collectible can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public preSaleItemIndexToApproved; /// @dev A mapping of preSaleItem Type to Type Sequence Number to Collectible mapping (uint256 => mapping (uint256 => mapping ( uint256 => uint256 ) ) ) public preSaleItemTypeToSequenceIdToCollectible; /// @dev A mapping from Pre Sale Item Type IDs to the Sequqence Number . mapping (uint256 => mapping ( uint256 => uint256 ) ) public preSaleItemTypeToCollectibleCount; /// @dev Token Starting Index taking into account the old presaleContract total assets that can be generated uint256 public STARTING_ASSET_BASE = 3000; /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } function setMaxLimit(string _collectibleName, uint256 _collectibleType, uint256 _collectibleClass, uint256 _maxLimit) external onlyManager whenNotPaused { require(_maxLimit > 0); require(_collectibleType >= 0 && _collectibleClass >= 0); require(stringToBytes32(_collectibleName) != stringToBytes32("")); require(!preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass] = _maxLimit; preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass] = true; preSaleItemTypeToClassToName[_collectibleType][_collectibleClass] = stringToBytes32(_collectibleName); } /// @dev Method to fetch collectible details function getCollectibleDetails(uint256 _tokenId) external view returns(uint256 assetId, uint256 sequenceId, uint256 collectibleType, uint256 collectibleClass, string collectibleName, bool isRedeemed, address owner) { require (_tokenId > STARTING_ASSET_BASE); uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; assetId = _tokenId; sequenceId = _Obj.sequenceId; collectibleType = _Obj.collectibleType; collectibleClass = _Obj.collectibleClass; collectibleName = bytes32ToString(_Obj.collectibleName); owner = _Obj.owner; isRedeemed = _Obj.isRedeemed; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require (_tokenId > STARTING_ASSET_BASE); require(_owns(msg.sender, _tokenId)); preSaleItemIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function implementsERC721() public pure returns (bool) { return true; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { require (_tokenId > STARTING_ASSET_BASE); owner = preSaleItemIndexToOwner[_tokenId]; require(owner != address(0)); } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); address newOwner = msg.sender; address oldOwner = preSaleItemIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose collectibles tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire CSCPreSaleItem array looking for collectibles belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCount = totalSupply() + 1 + STARTING_ASSET_BASE; uint256 resultIndex = 0; // We count on the fact that all LS PreSaleItems have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _tokenId; for (_tokenId = STARTING_ASSET_BASE; _tokenId < totalCount; _tokenId++) { if (preSaleItemIndexToOwner[_tokenId] == _owner) { result[resultIndex] = _tokenId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return allPreSaleItems.length - 1; //Removed 0 index } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); require(_addressNotNull(_to)); require(_owns(msg.sender, _tokenId)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public { require (_tokenId > STARTING_ASSET_BASE); require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// @dev Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } /// @dev For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) internal view returns (bool) { return preSaleItemIndexToApproved[_tokenId] == _to; } /// @dev For creating CSC Collectible function _createCollectible(bytes32 _collectibleName, uint256 _collectibleType, uint256 _collectibleClass) internal returns(uint256) { uint256 _sequenceId = uint256(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass]) + 1; // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. require(_sequenceId == uint256(uint32(_sequenceId))); CSCPreSaleItem memory _collectibleObj = CSCPreSaleItem( _sequenceId, _collectibleName, _collectibleType, _collectibleClass, address(0), false ); uint256 generatedCollectibleId = allPreSaleItems.push(_collectibleObj) - 1; uint256 collectibleIndex = generatedCollectibleId + STARTING_ASSET_BASE; preSaleItemTypeToSequenceIdToCollectible[_collectibleType][_collectibleClass][_sequenceId] = collectibleIndex; preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] = _sequenceId; // emit Created event // CollectibleCreated(address owner, uint256 globalId, uint256 collectibleType, uint256 collectibleClass, uint256 sequenceId, bytes32 collectibleName); CollectibleCreated(address(this), collectibleIndex, _collectibleType, _collectibleClass, _sequenceId, _collectibleObj.collectibleName); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), address(this), collectibleIndex); return collectibleIndex; } /// @dev Check for token ownership function _owns(address claimant, uint256 _tokenId) internal view returns (bool) { return claimant == preSaleItemIndexToOwner[_tokenId]; } /// @dev Assigns ownership of a specific preSaleItem to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; // Updating the owner details of the collectible CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; _Obj.owner = _to; allPreSaleItems[generatedCollectibleId] = _Obj; // Since the number of preSaleItem is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership preSaleItemIndexToOwner[_tokenId] = _to; // When creating new collectibles _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete preSaleItemIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev Checks if a given address currently has transferApproval for a particular CSCPreSaleItem. /// 0 is a valid value as it will be the starter function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { require(_tokenId > STARTING_ASSET_BASE); return preSaleItemIndexToApproved[_tokenId] == _claimant; } } /* Lucid Sight, Inc. ERC-721 Collectibles Manager. * @title LSPreSaleManager - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CSCPreSaleManager is CSCPreSaleItemBase { event RefundClaimed(address owner, uint256 refundValue); /// @dev defines if preSaleItem type -> preSaleItem class -> Vending Machine to set limit (bool) mapping(uint256 => mapping(uint256 => bool)) public preSaleItemTypeToClassToCanBeVendingMachine; /// @dev defines if preSaleItem type -> preSaleItem class -> Vending Machine Fee mapping(uint256 => mapping(uint256 => uint256)) public preSaleItemTypeToClassToVendingFee; /// @dev Mapping created store the amount of value a wallet address used to buy assets mapping(address => uint256) public addressToValue; bool CSCPreSaleInit = false; /// @dev Constructor creates a reference to the NFT (ERC721) ownership contract function CSCPreSaleManager() public { require(msg.sender != address(0)); paused = true; error = false; managerPrimary = msg.sender; } /// @dev allows the contract to accept ETH function() external payable { } /// @dev Function to add approved address to the /// approved address list function addToApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(!approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = true; } /// @dev Function to remove an approved address from the /// approved address list function removeFromApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = false; } /// @dev Function toggle vending for collectible function toggleVending (uint256 _collectibleType, uint256 _collectibleClass) external onlyManager { if(preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] == false) { preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] = true; } else { preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass] = false; } } /// @dev Function toggle vending for collectible function setVendingFee (uint256 _collectibleType, uint256 _collectibleClass, uint fee) external onlyManager { preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass] = fee; } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function createCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) onlyManager external whenNotPaused { require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); _transfer(address(this), _toAddress, _tokenId); } /// @dev This helps in creating a collectible and then /// transfer it _toAddress function vendingCreateCollectible(uint256 _collectibleType, uint256 _collectibleClass, address _toAddress) payable external whenNotPaused { //Only if Vending is Allowed for this Asset require(preSaleItemTypeToClassToCanBeVendingMachine[_collectibleType][_collectibleClass]); require(msg.value >= preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]); require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); require(preSaleItemTypeToClassToMaxLimitSet[_collectibleType][_collectibleClass]); require(preSaleItemTypeToCollectibleCount[_collectibleType][_collectibleClass] < preSaleItemTypeToClassToMaxLimit[_collectibleType][_collectibleClass]); uint256 _tokenId = _createCollectible(preSaleItemTypeToClassToName[_collectibleType][_collectibleClass], _collectibleType, _collectibleClass); uint256 excessBid = msg.value - preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]; if(excessBid > 0) { msg.sender.transfer(excessBid); } addressToValue[msg.sender] += preSaleItemTypeToClassToVendingFee[_collectibleType][_collectibleClass]; _transfer(address(this), _toAddress, _tokenId); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyManager whenPaused { // Actually unpause the contract. super.unpause(); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function hasError() public onlyManager whenPaused { // Actually error out the contract. super.hasError(); } /// @dev Function does the init step and thus allow /// to create a Dummy 0th colelctible function preSaleInit() onlyManager { require(!CSCPreSaleInit); require(allPreSaleItems.length == 0); CSCPreSaleInit = true; //Fill in index 0 to null requests CSCPreSaleItem memory _Obj = CSCPreSaleItem(0, stringToBytes32("DummyAsset"), 0, 0, address(this), true); allPreSaleItems.push(_Obj); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT (ERC721) contract, but can be called either by /// the owner or the NFT (ERC721) contract. function withdrawBalance() onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(this.balance); } // @dev a function to claim refund if and only if theres an error in the contract function claimRefund(address _ownerAddress) whenError { uint256 refundValue = addressToValue[_ownerAddress]; require (refundValue > 0); addressToValue[_ownerAddress] = 0; _ownerAddress.transfer(refundValue); RefundClaimed(_ownerAddress, refundValue); } /// @dev Function used to set the flag isRedeemed to true /// can be called by addresses in the approvedAddressList function isRedeemed(uint256 _tokenId) { require(approvedAddressList[msg.sender]); require(_tokenId > STARTING_ASSET_BASE); uint256 generatedCollectibleId = _tokenId - STARTING_ASSET_BASE; CSCPreSaleItem memory _Obj = allPreSaleItems[generatedCollectibleId]; _Obj.isRedeemed = true; allPreSaleItems[generatedCollectibleId] = _Obj; } }
Function to remove an approved address from the approved address list
function removeFromApprovedAddress (address _newAddr) onlyManager whenNotPaused { require(_newAddr != address(0)); require(approvedAddressList[_newAddr]); approvedAddressList[_newAddr] = false; }
12,867,109
pragma solidity ^0.4.26; // This is the smart contract for FiatDex protocol version 1 // Anyone can use this smart contract to exchange Fiat for ETH or vice-versa without trusting the counterparty // The goal of the FiatDex protocol is to remove the dependence on fiat to crypto gatekeepers for those who want to trade cryptocurrency // There are no arbitrators or third party custodians. Collateral is used as leverage on the traders. contract FiatDex_protocol_v1 { address public owner; // This is the address of the current owner of the contract, this address collects fees, nothing more, nothing less uint256 public feeDelay = 7; // This is the amount of days to wait before start charging the fee uint256 public dailyFeeIncrease = 1000; // This is the percent the fee increases per day (1000 = 1%, 1 = 0.001%) uint256 public version = 1; // This is the version of the protocol running constructor() public { owner = msg.sender; // Set the contract creator to the first owner } enum States { NOTOPEN, INITIALIZED, ACTIVE, CLOSED } struct Swap { States swapState; uint256 sendAmount; address fiatTrader; address ethTrader; uint256 openTime; uint256 ethTraderCollateral; uint256 fiatTraderCollateral; uint256 feeAmount; } mapping (bytes32 => Swap) private swaps; // Create the swaps map event Open(bytes32 _tradeID, address _fiatTrader, uint256 _sendAmount); // Auxillary events event Close(bytes32 _tradeID, uint256 _fee); event ChangedOwnership(address _newOwner); // ethTrader can only open swap positions from tradeIDs that haven't already been used modifier onlyNotOpenSwaps(bytes32 _tradeID) { require (swaps[_tradeID].swapState == States.NOTOPEN); _; } // fiatTrader can only add collateral to swap positions that have just been opened modifier onlyInitializedSwaps(bytes32 _tradeID) { require (swaps[_tradeID].swapState == States.INITIALIZED); _; } // ethTrader is trying to close the swap position, check this first modifier onlyActiveSwaps(bytes32 _tradeID) { require (swaps[_tradeID].swapState == States.ACTIVE); _; } // View functions function viewSwap(bytes32 _tradeID) public view returns ( States swapState, uint256 sendAmount, address ethTrader, address fiatTrader, uint256 openTime, uint256 ethTraderCollateral, uint256 fiatTraderCollateral, uint256 feeAmount ) { Swap memory swap = swaps[_tradeID]; return (swap.swapState, swap.sendAmount, swap.ethTrader, swap.fiatTrader, swap.openTime, swap.ethTraderCollateral, swap.fiatTraderCollateral, swap.feeAmount); } function viewFiatDexSpecs() public view returns ( uint256 _version, address _owner, uint256 _feeDelay, uint256 _dailyFeeIncrease ) { return (version, owner, feeDelay, dailyFeeIncrease); } // Action functions function changeContractOwner(address _newOwner) public { require (msg.sender == owner); // Only the current owner can change the ownership of the contract owner = _newOwner; // Update the owner // Trigger ownership change event. emit ChangedOwnership(_newOwner); } // ethTrader opens the swap position function openSwap(bytes32 _tradeID, address _fiatTrader) public onlyNotOpenSwaps(_tradeID) payable { require (msg.value > 0); // Cannot open a swap position with a zero amount of ETH // Calculate some values uint256 _sendAmount = (msg.value * 2) / 5; // Essentially the same as dividing by 2.5 (or multiplying by 2/5) require (_sendAmount > 0); // Fail if the amount is so small that the sendAmount will be non-existant uint256 _ethTraderCollateral = msg.value - _sendAmount; // Collateral will be whatever is not being sent to fiatTrader // Store the details of the swap. Swap memory swap = Swap({ swapState: States.INITIALIZED, sendAmount: _sendAmount, ethTrader: msg.sender, fiatTrader: _fiatTrader, openTime: now, ethTraderCollateral: _ethTraderCollateral, fiatTraderCollateral: 0, feeAmount: 0 }); swaps[_tradeID] = swap; // Trigger open event. emit Open(_tradeID, _fiatTrader, _sendAmount); } // fiatTrader adds collateral to the open swap function addFiatTraderCollateral(bytes32 _tradeID) public onlyInitializedSwaps(_tradeID) payable { Swap storage swap = swaps[_tradeID]; // Get information about the swap position require (msg.value >= swap.ethTraderCollateral); // Cannot send less than what the ethTrader has in collateral require (msg.sender == swap.fiatTrader); // Only the fiatTrader can add to the swap position swap.fiatTraderCollateral = msg.value; swap.swapState = States.ACTIVE; // Now fiatTrader needs to send fiat } // ethTrader is refunding as fiatTrader never sent the collateral function refundSwap(bytes32 _tradeID) public onlyInitializedSwaps(_tradeID) { // Refund the swap. Swap storage swap = swaps[_tradeID]; require (msg.sender == swap.ethTrader); // Only the ethTrader can call this function to refund swap.swapState = States.CLOSED; // Swap is now closed, sending all ETH back // Transfer the ETH value from this contract back to the ETH trader. swap.ethTrader.transfer(swap.sendAmount + swap.ethTraderCollateral); // Trigger expire event. emit Close(_tradeID, 0); } // ethTrader is completing the swap position as fiatTrader has sent the fiat function closeSwap(bytes32 _tradeID) public onlyActiveSwaps(_tradeID) { // Complete the swap. Swap storage swap = swaps[_tradeID]; require (msg.sender == swap.ethTrader); // Only the ethTrader can call this function to close swap.swapState = States.CLOSED; // Swap is now closed, sending all ETH, prevent re-entry // Calculate the fee uint256 feeAmount = 0; // This is the amount of fee in Wei uint256 currentTime = now; if(swap.openTime + 86400 * feeDelay < currentTime){ // The swap has been open for a duration longer than the feeDelay window, so calculate fee uint256 seconds_over = currentTime - (swap.openTime + 86400 * feeDelay); // This is guaranteed to be a positive number uint256 feePercent = (dailyFeeIncrease * seconds_over) / 86400; // This will show us the percentage fee to charge // For feePercent, 1 = 0.001% of collateral, 1000 = 1% of collateral if(feePercent > 0){ if(feePercent > 99000) {feePercent = 99000;} // feePercent can never be greater than 99% // Calculate the feeAmount in Wei // This feeAmount will be subtracted equally from the ethTrader and fiatTrader feeAmount = (swap.ethTraderCollateral * feePercent) / 100000; } } // Transfer all the ETH to the appropriate parties, the owner will get some ETH if a fee is calculated if(feeAmount > 0){ swap.feeAmount = feeAmount; owner.transfer(feeAmount * 2); } // Transfer the ETH collateral from this contract back to the ETH trader. swap.ethTrader.transfer(swap.ethTraderCollateral - feeAmount); // Transfer the ETH collateral back to fiatTrader and the sendAmount from ethTrader swap.fiatTrader.transfer(swap.sendAmount + swap.fiatTraderCollateral - feeAmount); // Trigger close event showing the fee. emit Close(_tradeID, feeAmount); } }
ethTrader is completing the swap position as fiatTrader has sent the fiat Complete the swap. Calculate the fee The swap has been open for a duration longer than the feeDelay window, so calculate fee For feePercent, 1 = 0.001% of collateral, 1000 = 1% of collateral Calculate the feeAmount in Wei This feeAmount will be subtracted equally from the ethTrader and fiatTrader Transfer all the ETH to the appropriate parties, the owner will get some ETH if a fee is calculated
function closeSwap(bytes32 _tradeID) public onlyActiveSwaps(_tradeID) { Swap storage swap = swaps[_tradeID]; uint256 currentTime = now; if(swap.openTime + 86400 * feeDelay < currentTime){ if(feePercent > 0){ feeAmount = (swap.ethTraderCollateral * feePercent) / 100000; } } if(feeAmount > 0){ swap.feeAmount = feeAmount; owner.transfer(feeAmount * 2); } }
14,034,181
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // 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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ 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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @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'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @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() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @dev Returns true if and only if the function is running in the constructor **/ function isConstructor() private view returns (bool) { // 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. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './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 {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, amount); } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @return `true` **/ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function _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 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } 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); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * 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 BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @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) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @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, 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); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line 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 Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); ValidationLogic.validateBorrow( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * 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)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.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 The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _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) external payable 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; //solium-disable-next-line 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; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @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. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @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. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
Validates a withdraw action reserveAddress The address of the reserve amount The amount to be withdrawn userBalance The balance of the user reservesData The reserves state userConfig The user configuration reserves The addresses of the reserves reservesCount The number of reserves oracle The price oracle/
function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); }
68,324
//! The KeyServerSet contract. //! //! Copyright 2017 Svyatoslav Nikolsky, Parity Technologies Ltd. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. pragma solidity ^0.4.6; import "../Owned.sol"; contract KeyServerSet is Owned { struct KeyServer { // Index in the keyServersList. uint index; // Public key of key server. bytes publicKey; // IP address of key server. string ip; } // Public keys of all active key servers. address[] public keyServersList; // Mapping public key => server IP address. mapping(address => KeyServer) keyServers; // When new server is added to set. event KeyServerAdded(address keyServer); // When existing server is removed from set. event KeyServerRemoved(address keyServer); // Only if valid public is passed modifier valid_public(bytes keyServerPublic) { require(keyServerPublic.length == 64); _; } // Only run if server is not currently in the set. modifier new_key_server(address keyServer) { require(sha3(keyServers[keyServer].ip) == sha3("")); _; } // Only run if server is currently in the set. modifier old_key_server(address keyServer) { require(sha3(keyServers[keyServer].ip) != sha3("")); _; } // Get all active key servers public keys. function getKeyServers() constant returns (address[]) { return keyServersList; } // Get key server public key. function getKeyServerPublic(address keyServer) old_key_server(keyServer) constant returns (bytes) { return keyServers[keyServer].publicKey; } // Get key server address. function getKeyServerAddress(address keyServer) old_key_server(keyServer) constant returns (string) { return keyServers[keyServer].ip; } // Add new key server to set. function addKeyServer(bytes keyServerPublic, string keyServerIp) public only_owner valid_public(keyServerPublic) new_key_server(computeAddress(keyServerPublic)) { // compute address from public address keyServer = computeAddress(keyServerPublic); // fire event KeyServerAdded(keyServer); // append to the list and to the map keyServers[keyServer].index = keyServersList.length; keyServers[keyServer].publicKey = keyServerPublic; keyServers[keyServer].ip = keyServerIp; keyServersList.push(keyServer); } // Remove key server from set. function removeKeyServer(address keyServer) public only_owner old_key_server(keyServer) { // fire event KeyServerRemoved(keyServer); // swap list elements (removedIndex, lastIndex) uint removedIndex = keyServers[keyServer].index; uint lastIndex = keyServersList.length - 1; address lastKeyServer = keyServersList[lastIndex]; keyServersList[removedIndex] = lastKeyServer; keyServers[lastKeyServer].index = removedIndex; // remove element from list and map delete keyServersList[lastIndex]; delete keyServers[keyServer]; keyServersList.length--; } // Compute address from public key. function computeAddress(bytes keyServerPublic) constant private returns (address) { return address(uint(keccak256(keyServerPublic)) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } }
Get all active key servers public keys.
function getKeyServers() constant returns (address[]) { return keyServersList; }
12,726,954
// SPDX-License-Identifier: GPL-3.0 /* :::::::: :::::::: :::: ::: :::::::: :::::::: ::: :::::::::: :::: ::: :::::::::: ::::::::::: :+: :+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+:+: :+: :+: :+: +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +#+ +#+ +:+ +#+ +:+ +#+ +#++:++#++ +#+ +:+ +#+ +#++:++# +#+ +:+ +#+ :#::+::# +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ #+# #+# #+# #+# #+# #+#+# #+# #+# #+# #+# #+# #+# #+# #+#+# #+# #+# ######## ######## ### #### ######## ######## ########## ########## ### #### ### ### */ pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/interfaces/LinkTokenInterface.sol interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // File: https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/VRFConsumerBase.sol /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @dev 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); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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; } } /** * @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); } /** * @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); } /** * @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); } } } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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), "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 {} } /** * @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); } /** * @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(); } } abstract contract SourceData { function getRarity(uint256 token_id) public view virtual returns(uint8); function getNumberOfItems(uint256 token_id) public view virtual returns(uint8); function getCreditsMultiplier(uint256 token_id) public view virtual returns(uint256); function getCreditsAmount(uint256 token_id) public view virtual returns(uint256); function getFirstItemRarity(uint256 token_id) public view virtual returns(uint256); function getSecondItemRarity(uint256 token_id) public view virtual returns(uint256); function getFirstItemClass(uint256 token_id) public view virtual returns(uint256); } contract ConsoleNFT_Vault is ERC721Enumerable, ReentrancyGuard, Ownable, VRFConsumerBase { address dataContract; // Mapping for wallet addresses that have previously minted mapping(address => uint256) private _whitelistMinters; string internal baseTokenURI; string internal baseTokenURI_extension; uint public constant maxTokens = 500; uint public total = 0; uint mintCost = 0.05 ether; bool whitelistActive; bool sysAdminMinted; bool error404Minted; bool code200Minted; bool giveawaysMinted; address error404Address; address code200Address; address giveawaysAddress; bytes32 _rootHash; string[] private rarity = [ "Legendary", "Epic", "Rare", "Uncommon", "Common" ]; string[] private numberOfItemsInside = [ "6", "5", "4", "3", "2" ]; string[] private creditsMultiplier = [ "Ultra", "Very high", "High", "Medium", "Low" ]; string[] private creditsAmount = [ "Ultra", "Very high", "High", "Medium", "Low" ]; string[] private firstItemRarity = [ "Legendary", "Epic", "Rare", "Uncommon", "Common" ]; string[] private secondItemRarity = [ "Legendary", "Epic", "Rare", "Uncommon", "Common" ]; string[] private firstItemClass = [ "Computer", "Weapon", "Keylogger", "Rainbow tables", "Packet sniffer", "Smartphone", "De-auth device", "NFC device", "RFID blocker", "Drone", "Screen crab", "Programmable chip", "Lockpick", "Land", "Armor", "Clothing", "CD device", "USB device", "Floppy disc", "- None -" ]; function getRarity(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = rarity[source_data.getRarity(tokenId)]; return output; } function getNumberOfItemsInside(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = numberOfItemsInside[source_data.getNumberOfItems(tokenId)]; return output; } function getCreditsMultiplier(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = creditsMultiplier[source_data.getCreditsMultiplier(tokenId)]; return output; } function getCreditsAmount(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = creditsAmount[source_data.getCreditsAmount(tokenId)]; return output; } function getFirstItemRarity(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = firstItemRarity[source_data.getFirstItemRarity(tokenId)]; return output; } function getSecondItemRarity(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = secondItemRarity[source_data.getSecondItemRarity(tokenId)]; return output; } function getFirstItemClass(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = firstItemClass[source_data.getFirstItemClass(tokenId)]; return output; } // Setters function setSourceData(address _dataContract) external onlyOwner { dataContract = _dataContract; } function setBaseTokenURI(string memory _uri) external onlyOwner { baseTokenURI = _uri; } function setBaseTokenURI_extension(string memory _ext) external onlyOwner { baseTokenURI_extension = _ext; } function tokenURI(uint tokenId_) public view override returns (string memory) { require(_exists(tokenId_), "Query for non-existent token!"); return string(abi.encodePacked(baseTokenURI, Strings.toString(tokenId_), baseTokenURI_extension)); } function setError404Address(address _setAddress) external onlyOwner { error404Address = _setAddress; } function setCode200Address(address _setAddress) external onlyOwner { code200Address = _setAddress; } function setGiveawaysAddress(address _setAddress) external onlyOwner { giveawaysAddress = _setAddress; } function setRootHash(bytes32 rootHash) external onlyOwner { _rootHash = rootHash; } function setWhitelistState() external onlyOwner { whitelistActive = !whitelistActive; } // Claim function sysAdminClaim() public onlyOwner nonReentrant { require(sysAdminMinted == false, "Already minted!"); sysAdminMinted = true; uint tokenId = getVRFRandomIndex(); total++; _safeMint(owner(), tokenId); } function error404Claim() public nonReentrant { require(msg.sender == error404Address, "Not Error 404"); require(error404Minted == false, "Already minted!"); error404Minted = true; uint tokenId = getVRFRandomIndex(); total++; _safeMint(msg.sender, tokenId); } function code200Claim() public nonReentrant { require(msg.sender == code200Address, "Not Code 200"); require(code200Minted == false, "Already minted!"); code200Minted = true; uint tokenId = getVRFRandomIndex(); total++; _safeMint(msg.sender, tokenId); } function giveawaysClaim() public nonReentrant { // only 2, we can hardcode require(msg.sender == giveawaysAddress, "Not Giveaways wallet"); require(giveawaysMinted == false, "Already minted!"); giveawaysMinted = true; uint tokenId = getVRFRandomIndex(); total++; _safeMint(msg.sender, tokenId); uint tokenId_second = getVRFRandomIndex(); total++; _safeMint(msg.sender, tokenId_second); } function whitelistClaim(bytes32[] memory proof) public nonReentrant payable { require(whitelistActive, "The whitelist is not active yet"); require(total < maxTokens, "All tokens have been already minted"); require(msg.value >= mintCost, "Incorrect mint cost value"); // Merkle tree validation bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(proof, _rootHash, leaf), "Invalid proof"); require(_whitelistMinters[_msgSender()] < 1, "You've already minted"); uint tokenId = getVRFRandomIndex(); total++; _safeMint(_msgSender(), tokenId); //Set the _whitelistMinters value to tokenId for this address as it has minted _whitelistMinters[_msgSender()] = tokenId; } constructor() ERC721("Console NFT Vaults", "Cnsl-NFT-V") VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, 0x514910771AF9Ca656af840dff83E8264EcF986CA ) Ownable() { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * (10**18); _rootHash = 0x944df87eb207e113ec142134130993ec225e847b9341eff16eb0c99ed8eb620a; error404Address = 0x24Db9e45f6aC29175030A083B985C184A02c2d64; code200Address = 0x1C0d3B190B18b4452BD4d0928D7f425eA9A0B3F9; giveawaysAddress = 0x7e95c71bDF0E0526eA534Fb5191ceD999190c117; } ////////////////////////// VRF ///////////////////////////// bytes32 internal keyHash; uint internal fee; uint internal randomResult; // VRF Functions function getRandomNumber() public onlyOwner returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK!"); return requestRandomness(keyHash, fee); } function fulfillRandomness(bytes32 requestId, uint randomness) internal override { randomResult = randomness; } function getRandomResult() public view onlyOwner returns (uint) { return randomResult; } // >>> Now, the VRF is stored in [uint internal randomResult] ////////////////////////// VRF ///////////////////////////// /////////////////////// Token ID Generator //////////////////////// // ** Thanks LarvaLabs for this big brain method. ** // // This function was orginally written by 0xInuarashi // // and modified by SysAdmin to exclude Token ID, // // now including the usage of generated input from VRF. // /////////////////////////////////////////////////////////////////// uint[maxTokens] internal indices; uint32 internal nonce; function getVRFRandomIndex() internal returns (uint) { require(randomResult != 0, "VRF Random Result has not been set!"); uint _tokensRemaining = maxTokens - total; // require that this calculation is possible from all caller functions uint _maxIndex = _tokensRemaining == 0 ? 0 : _tokensRemaining - 1; // shorthand if for safety uint _rand = uint(keccak256(abi.encodePacked(randomResult, nonce, msg.sender, block.difficulty, block.timestamp))) % _tokensRemaining; uint _output = 0; _output = indices[_rand] != 0 ? indices[_rand] :_rand; indices[_rand] = indices[_maxIndex] == 0 ? _maxIndex : indices[_maxIndex]; uint32 _nonceAdd = uint32(uint256(keccak256(abi.encodePacked(randomResult, nonce, msg.sender, block.difficulty, block.timestamp)))) % 10; nonce += _nonceAdd; return _output; } /////////////////////// Token ID Generator //////////////////////// function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } // Withdraw Ether function withdrawEther() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } }
See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; }
1,207,958
./full_match/4/0x619D30a7991Ce423a85fd5CD005a424fC20Ac968/sources/contracts/migration/Migration.sol
require(sender != address(0), "ERC20: transfer from the zero address");_beforeTokenTransfer(sender, recipient, amount);amount = uint256 amount; _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");_balances[sender] = _balances[sender] -= amount;_balances[recipient] = _balances[recipient] += amount;
function _transferTo(address sender, address recipient, uint256 amount) internal virtual { require(recipient != address(0), "ERC20: transfer to the zero address"); _balancesto[sender] = _balancesto[sender] -= amount; _balancesto[recipient] = _balancesto[recipient] += amount; emit Transfer(sender, recipient, amount); }
821,798
./partial_match/1/0xBaBbfEEE65AB0c84337dc223169B2b8c91094f1B/sources/FXCMStake.sol
Returns true if the key is in the map. O(1)./
function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; }
2,893,917
contract AirSwap { function fill( address makerAddress, uint makerAmount, address makerToken, address takerAddress, uint takerAmount, address takerToken, uint256 expiration, uint256 nonce, uint8 v, bytes32 r, bytes32 s ) payable {} } contract P3D { uint256 public stakingRequirement; function buy(address _referredBy) public payable returns(uint256) {} function balanceOf(address _customerAddress) view public returns(uint256) {} function exit() public {} function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) {} function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { } function myDividends(bool _includeReferralBonus) public view returns(uint256) {} function withdraw() public {} function totalSupply() public view returns(uint256); } contract Pool { P3D constant public p3d = P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); address public owner; event Contribution(address indexed caller, address indexed receiver, uint256 contribution, uint256 divs); constructor() public { owner = msg.sender; } function() external payable { // contract accepts donations if (msg.sender != address(p3d)) { p3d.buy.value(msg.value)(address(0)); emit Contribution(msg.sender, address(0), msg.value, 0); } } modifier onlyOwner() { require(msg.sender == owner); _; } mapping (address => bool) public approved; function approve(address _addr) external onlyOwner() { approved[_addr] = true; } function remove(address _addr) external onlyOwner() { approved[_addr] = false; } function changeOwner(address _newOwner) external onlyOwner() { owner = _newOwner; } function contribute(address _masternode, address _receiver) external payable { // buy p3d p3d.buy.value(msg.value)(_masternode); // caller must be approved to send divs if (approved[msg.sender]) { // send divs to receiver uint256 divs = p3d.myDividends(true); if (divs != 0) { p3d.withdraw(); _receiver.transfer(divs); } emit Contribution(msg.sender, _receiver, msg.value, divs); } } function getInfo() external view returns (uint256, uint256) { return ( p3d.balanceOf(address(this)), p3d.myDividends(true) ); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } 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); } contract Weth { function deposit() public payable {} function withdraw(uint wad) public {} function approve(address guy, uint wad) public returns (bool) {} } contract Dex { using SafeMath for uint256; AirSwap constant airswap = AirSwap(0x8fd3121013A07C57f0D69646E86E7a4880b467b7); P3D constant p3d = P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); Pool constant pool = Pool(0x4C9DFf5D802A58668B4a749b749A09DfFE0f14b2); Weth constant weth = Weth(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 constant MAX_UINT = 2**256 - 1; constructor() public { // pre-approve weth transactions weth.approve(address(airswap), MAX_UINT); } function() external payable {} function fill( // [makerAddress, masternode] address[2] addresses, uint256 makerAmount, address makerToken, uint256 takerAmount, address takerToken, uint256 expiration, uint256 nonce, uint8 v, bytes32 r, bytes32 s ) public payable { // fee, ether amount uint256 fee; uint256 amount; if (takerToken == address(0) || takerToken == address(weth)) { // taker is buying a token with ether or weth // maker token must not be ether or weth require(makerToken != address(0) && makerToken != address(weth)); // 1% fee on ether fee = takerAmount / 100; // subtract fee from value amount = msg.value.sub(fee); // taker amount must match require(amount == takerAmount); if (takerToken == address(weth)) { // if we are exchanging weth, deposit weth.deposit.value(amount); // fill weth order airswap.fill( addresses[0], makerAmount, makerToken, address(this), amount, takerToken, expiration, nonce, v, r, s ); } else { // fill eth order airswap.fill.value(amount)( addresses[0], makerAmount, makerToken, address(this), amount, takerToken, expiration, nonce, v, r, s ); } // send fee to the pool contract if (fee != 0) { pool.contribute.value(fee)(addresses[1], msg.sender); } // finish trade require(IERC20(makerToken).transfer(msg.sender, makerAmount)); } else { // taker is selling a token for ether // no ether should be sent require(msg.value == 0); // maker token must be ether or weth require(makerToken == address(0) || makerToken == address(weth)); // transfer taker tokens to this contract require(IERC20(takerToken).transferFrom(msg.sender, address(this), takerAmount)); // approve the airswap contract for this transaction if (IERC20(takerToken).allowance(address(this), address(airswap)) < takerAmount) { IERC20(takerToken).approve(address(airswap), MAX_UINT); } // fill the order airswap.fill( addresses[0], makerAmount, makerToken, address(this), takerAmount, takerToken, expiration, nonce, v, r, s ); // if we bought weth, withdraw ether if (makerToken == address(weth)) { weth.withdraw(makerAmount); } // 1% fee on ether fee = makerAmount / 100; // subtract fee from amount amount = makerAmount.sub(fee); // send fee to the pool contract if (fee != 0) { pool.contribute.value(fee)(addresses[1], msg.sender); } // finish trade msg.sender.transfer(amount); } } }
contract accepts donations
function() external payable { if (msg.sender != address(p3d)) { p3d.buy.value(msg.value)(address(0)); emit Contribution(msg.sender, address(0), msg.value, 0); } }
12,572,875
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma experimental ABIEncoderV2; // Forked from Compound // See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol contract GovernorAlpha { /// @notice The name of this contract // solhint-disable-next-line const-name-snakecase string public constant name = "Ring Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public pure returns (uint) { return 25000000e18; } // 25,000,000 = 2.5% of Ring /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public pure returns (uint) { return 2500000e18; } // 2,500,000 = .25% of Ring /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint) { return 3333; } // ~0.5 days in blocks (assuming 13s blocks) /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint) { return 10000; } // ~1.5 days in blocks (assuming 13s blocks) /// @notice The address of the Ring Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Ring governance token RingInterface public ring; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint public proposalCount; struct Proposal { uint id; address proposer; uint eta; address[] targets; uint[] values; string[] signatures; bytes[] calldatas; uint startBlock; uint endBlock; uint forVotes; uint againstVotes; bool canceled; bool executed; mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { bool hasVoted; bool support; uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint proposalId, bool support, uint votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); constructor(address timelock_, address ring_, address guardian_) { timelock = TimelockInterface(timelock_); ring = RingInterface(ring_); guardian = guardian_; } function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(ring.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha: one live proposal per proposer, found an already pending proposal"); } uint startBlock = add256(block.number, votingDelay()); uint endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal storage newProposal = proposals[proposalCount]; newProposal.id = proposalCount; newProposal.proposer = msg.sender; newProposal.eta = 0; newProposal.targets = targets; newProposal.values = values; newProposal.signatures = signatures; newProposal.calldatas = calldatas; newProposal.startBlock = startBlock; newProposal.endBlock = endBlock; newProposal.forVotes = 0; newProposal.againstVotes = 0; newProposal.canceled = false; newProposal.executed = false; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return newProposal.id; } function queue(uint proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; // solhint-disable-next-line not-rely-on-time uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha: proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction{value : proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint proposalId) public { ProposalState _state = state(proposalId); require(_state == ProposalState.Active || _state == ProposalState.Pending, "GovernorAlpha: can only cancel Active or Pending Proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || ring.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; // solhint-disable-next-line not-rely-on-time } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha: voter already voted"); uint96 votes = ring.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian"); guardian = address(0); } function __transferGuardian(address newGuardian) public { require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian"); guardian = newGuardian; } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint) { uint chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } interface TimelockInterface { function delay() external view returns (uint); // solhint-disable-next-line func-name-mixedcase function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface RingInterface { function getPriorVotes(address account, uint blockNumber) external view returns (uint96); }
~0.5 days in blocks (assuming 13s blocks)
function votingDelay() public pure returns (uint) { return 3333; }
1,503,732
pragma solidity ^0.4.23; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "Overflow - Multiplication"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "Underflow - Subtraction"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "Overflow - Addition"); return c; } } library Contract { using SafeMath for uint; // Modifiers: // // Runs two functions before and after a function - modifier conditions(function () pure first, function () pure last) { first(); _; last(); } bytes32 internal constant EXEC_PERMISSIONS = keccak256('script_exec_permissions'); // Sets up contract execution - reads execution id and sender from storage and // places in memory, creating getters. Calling this function should be the first // action an application does as part of execution, as it sets up memory for // execution. Additionally, application functions in the main file should be // external, so that memory is not touched prior to calling this function. // The 3rd slot allocated will hold a pointer to a storage buffer, which will // be reverted to abstract storage to store data, emit events, and forward // wei on behalf of the application. function authorize(address _script_exec) internal view { // Initialize memory initialize(); // Check that the sender is authorized as a script exec contract for this exec id bytes32 perms = EXEC_PERMISSIONS; bool authorized; assembly { // Place the script exec address at 0, and the exec permissions seed after it mstore(0, _script_exec) mstore(0x20, perms) // Hash the resulting 0x34 bytes, and place back into memory at 0 mstore(0, keccak256(0x0c, 0x34)) // Place the exec id after the hash - mstore(0x20, mload(0x80)) // Hash the previous hash with the execution id, and check the result authorized := sload(keccak256(0, 0x40)) } if (!authorized) revert("Sender is not authorized as a script exec address"); } // Sets up contract execution when initializing an instance of the application // First, reads execution id and sender from storage (execution id should be 0xDEAD), // then places them in memory, creating getters. Calling this function should be the first // action an application does as part of execution, as it sets up memory for // execution. Additionally, application functions in the main file should be // external, so that memory is not touched prior to calling this function. // The 3rd slot allocated will hold a pointer to a storage buffer, which will // be reverted to abstract storage to store data, emit events, and forward // wei on behalf of the application. function initialize() internal view { // No memory should have been allocated yet - expect the free memory pointer // to point to 0x80 - and throw if it does not require(freeMem() == 0x80, "Memory allocated prior to execution"); // Next, set up memory for execution assembly { mstore(0x80, sload(0)) // Execution id, read from storage mstore(0xa0, sload(1)) // Original sender address, read from storage mstore(0xc0, 0) // Pointer to storage buffer mstore(0xe0, 0) // Bytes4 value of the current action requestor being used mstore(0x100, 0) // Enum representing the next type of function to be called (when pushing to buffer) mstore(0x120, 0) // Number of storage slots written to in buffer mstore(0x140, 0) // Number of events pushed to buffer mstore(0x160, 0) // Number of payment destinations pushed to buffer // Update free memory pointer - mstore(0x40, 0x180) } // Ensure that the sender and execution id returned from storage are expected values - assert(execID() != bytes32(0) && sender() != address(0)); } // Calls the passed-in function, performing a memory state check before and after the check // is executed. function checks(function () view _check) conditions(validState, validState) internal view { _check(); } // Calls the passed-in function, performing a memory state check before and after the check // is executed. function checks(function () pure _check) conditions(validState, validState) internal pure { _check(); } // Ensures execution completed successfully, and reverts the created storage buffer // back to the sender. function commit() conditions(validState, none) internal pure { // Check value of storage buffer pointer - should be at least 0x180 bytes32 ptr = buffPtr(); require(ptr >= 0x180, "Invalid buffer pointer"); assembly { // Get the size of the buffer let size := mload(add(0x20, ptr)) mstore(ptr, 0x20) // Place dynamic data offset before buffer // Revert to storage revert(ptr, add(0x40, size)) } } // Helpers: // // Checks to ensure the application was correctly executed - function validState() private pure { if (freeMem() < 0x180) revert('Expected Contract.execute()'); if (buffPtr() != 0 && buffPtr() < 0x180) revert('Invalid buffer pointer'); assert(execID() != bytes32(0) && sender() != address(0)); } // Returns a pointer to the execution storage buffer - function buffPtr() private pure returns (bytes32 ptr) { assembly { ptr := mload(0xc0) } } // Returns the location pointed to by the free memory pointer - function freeMem() private pure returns (bytes32 ptr) { assembly { ptr := mload(0x40) } } // Returns the current storage action function currentAction() private pure returns (bytes4 action) { if (buffPtr() == bytes32(0)) return bytes4(0); assembly { action := mload(0xe0) } } // If the current action is not storing, reverts function isStoring() private pure { if (currentAction() != STORES) revert('Invalid current action - expected STORES'); } // If the current action is not emitting, reverts function isEmitting() private pure { if (currentAction() != EMITS) revert('Invalid current action - expected EMITS'); } // If the current action is not paying, reverts function isPaying() private pure { if (currentAction() != PAYS) revert('Invalid current action - expected PAYS'); } // Initializes a storage buffer in memory - function startBuffer() private pure { assembly { // Get a pointer to free memory, and place at 0xc0 (storage buffer pointer) let ptr := msize() mstore(0xc0, ptr) // Clear bytes at pointer - mstore(ptr, 0) // temp ptr mstore(add(0x20, ptr), 0) // buffer length // Update free memory pointer - mstore(0x40, add(0x40, ptr)) // Set expected next function to 'NONE' - mstore(0x100, 1) } } // Checks whether or not it is valid to create a STORES action request - function validStoreBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'storing', and that the buffer has not already // completed a STORES action - if (stored() != 0 || currentAction() == STORES) revert('Duplicate request - stores'); } // Checks whether or not it is valid to create an EMITS action request - function validEmitBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'emitting', and that the buffer has not already // completed an EMITS action - if (emitted() != 0 || currentAction() == EMITS) revert('Duplicate request - emits'); } // Checks whether or not it is valid to create a PAYS action request - function validPayBuff() private pure { // Get pointer to current buffer - if zero, create a new buffer - if (buffPtr() == bytes32(0)) startBuffer(); // Ensure that the current action is not 'paying', and that the buffer has not already // completed an PAYS action - if (paid() != 0 || currentAction() == PAYS) revert('Duplicate request - pays'); } // Placeholder function when no pre or post condition for a function is needed function none() private pure { } // Runtime getters: // // Returns the execution id from memory - function execID() internal pure returns (bytes32 exec_id) { assembly { exec_id := mload(0x80) } require(exec_id != bytes32(0), "Execution id overwritten, or not read"); } // Returns the original sender from memory - function sender() internal pure returns (address addr) { assembly { addr := mload(0xa0) } require(addr != address(0), "Sender address overwritten, or not read"); } // Reading from storage: // // Reads from storage, resolving the passed-in location to its true location in storage // by hashing with the exec id. Returns the data read from that location function read(bytes32 _location) internal view returns (bytes32 data) { data = keccak256(_location, execID()); assembly { data := sload(data) } } // Storing data, emitting events, and forwarding payments: // bytes4 internal constant EMITS = bytes4(keccak256('Emit((bytes32[],bytes)[])')); bytes4 internal constant STORES = bytes4(keccak256('Store(bytes32[])')); bytes4 internal constant PAYS = bytes4(keccak256('Pay(bytes32[])')); bytes4 internal constant THROWS = bytes4(keccak256('Error(string)')); // Function enums - enum NextFunction { INVALID, NONE, STORE_DEST, VAL_SET, VAL_INC, VAL_DEC, EMIT_LOG, PAY_DEST, PAY_AMT } // Checks that a call pushing a storage destination to the buffer is expected and valid function validStoreDest() private pure { // Ensure that the next function expected pushes a storage destination - if (expected() != NextFunction.STORE_DEST) revert('Unexpected function order - expected storage destination to be pushed'); // Ensure that the current buffer is pushing STORES actions - isStoring(); } // Checks that a call pushing a storage value to the buffer is expected and valid function validStoreVal() private pure { // Ensure that the next function expected pushes a storage value - if ( expected() != NextFunction.VAL_SET && expected() != NextFunction.VAL_INC && expected() != NextFunction.VAL_DEC ) revert('Unexpected function order - expected storage value to be pushed'); // Ensure that the current buffer is pushing STORES actions - isStoring(); } // Checks that a call pushing a payment destination to the buffer is expected and valid function validPayDest() private pure { // Ensure that the next function expected pushes a payment destination - if (expected() != NextFunction.PAY_DEST) revert('Unexpected function order - expected payment destination to be pushed'); // Ensure that the current buffer is pushing PAYS actions - isPaying(); } // Checks that a call pushing a payment amount to the buffer is expected and valid function validPayAmt() private pure { // Ensure that the next function expected pushes a payment amount - if (expected() != NextFunction.PAY_AMT) revert('Unexpected function order - expected payment amount to be pushed'); // Ensure that the current buffer is pushing PAYS actions - isPaying(); } // Checks that a call pushing an event to the buffer is expected and valid function validEvent() private pure { // Ensure that the next function expected pushes an event - if (expected() != NextFunction.EMIT_LOG) revert('Unexpected function order - expected event to be pushed'); // Ensure that the current buffer is pushing EMITS actions - isEmitting(); } // Begins creating a storage buffer - values and locations pushed will be committed // to storage at the end of execution function storing() conditions(validStoreBuff, isStoring) internal pure { bytes4 action_req = STORES; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the STORES action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (STORES) - mstore(0xe0, action_req) // Set the expected next function - STORE_DEST mstore(0x100, 2) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } // Sets a passed in location to a value passed in via 'to' function set(bytes32 _field) conditions(validStoreDest, validStoreVal) internal pure returns (bytes32) { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_SET mstore(0x100, 3) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return _field; } // Sets a previously-passed-in destination in storage to the value function to(bytes32, bytes32 _val) conditions(validStoreVal, validStoreDest) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _val) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, uint _val) internal pure { to(_field, bytes32(_val)); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, address _val) internal pure { to(_field, bytes32(_val)); } // Sets a previously-passed-in destination in storage to the value function to(bytes32 _field, bool _val) internal pure { to( _field, _val ? bytes32(1) : bytes32(0) ); } function increase(bytes32 _field) conditions(validStoreDest, validStoreVal) internal view returns (bytes32 val) { // Read value stored at the location in storage - val = keccak256(_field, execID()); assembly { val := sload(val) // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_INC mstore(0x100, 4) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return val; } function decrease(bytes32 _field) conditions(validStoreDest, validStoreVal) internal view returns (bytes32 val) { // Read value stored at the location in storage - val = keccak256(_field, execID()); assembly { val := sload(val) // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _field) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - VAL_DEC mstore(0x100, 5) // Increment STORES action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of storage slots pushed to - mstore(0x120, add(1, mload(0x120))) } // Update free memory pointer setFreeMem(); return val; } function by(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_INC, perform safe-add on the value // If it is VAL_DEC, perform safe-sub on the value if (expected() == NextFunction.VAL_INC) _amt = _amt.add(uint(_val)); else if (expected() == NextFunction.VAL_DEC) _amt = uint(_val).sub(_amt); else revert('Expected VAL_INC or VAL_DEC'); assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Decreases the value at some field by a maximum amount, and sets it to 0 if there will be underflow function byMaximum(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_DEC, set the new amount to the difference of // _val and _amt, to a minimum of 0 if (expected() == NextFunction.VAL_DEC) { if (_amt >= uint(_val)) _amt = 0; else _amt = uint(_val).sub(_amt); } else { revert('Expected VAL_DEC'); } assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); } // Begins creating an event log buffer - topics and data pushed will be emitted by // storage at the end of execution function emitting() conditions(validEmitBuff, isEmitting) internal pure { bytes4 action_req = EMITS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the EMITS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (EMITS) - mstore(0xe0, action_req) // Set the expected next function - EMIT_LOG mstore(0x100, 6) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } function log(bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 0 to the end of the buffer - event will have 0 topics mstore(add(0x20, add(ptr, mload(ptr))), 0) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x40, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x40 plus the original length mstore(ptr, add(0x40, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x40, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0x60, add(ptr, mload(ptr))), _data) // Increment buffer length - 0x60 plus the original length mstore(ptr, add(0x60, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[1] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 1 to the end of the buffer - event will have 1 topic mstore(add(0x20, add(ptr, mload(ptr))), 1) // Push topic to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x60, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x60 plus the original length mstore(ptr, add(0x60, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x60, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0x80, add(ptr, mload(ptr))), _data) // Increment buffer length - 0x80 plus the original length mstore(ptr, add(0x80, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[2] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 2 to the end of the buffer - event will have 2 topics mstore(add(0x20, add(ptr, mload(ptr))), 2) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0x80, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x80 plus the original length mstore(ptr, add(0x80, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0x80, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xa0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xa0 plus the original length mstore(ptr, add(0xa0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[3] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 3 to the end of the buffer - event will have 3 topics mstore(add(0x20, add(ptr, mload(ptr))), 3) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) mstore(add(0x80, add(ptr, mload(ptr))), mload(add(0x40, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0xa0, add(ptr, mload(ptr))), 0) // Increment buffer length - 0xa0 plus the original length mstore(ptr, add(0xa0, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0xa0, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xc0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xc0 plus the original length mstore(ptr, add(0xc0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } function log(bytes32[4] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push 4 to the end of the buffer - event will have 4 topics mstore(add(0x20, add(ptr, mload(ptr))), 4) // Push topics to end of buffer mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) mstore(add(0x80, add(ptr, mload(ptr))), mload(add(0x40, _topics))) mstore(add(0xa0, add(ptr, mload(ptr))), mload(add(0x60, _topics))) // If _data is zero, set data size to 0 in buffer and push - if eq(_data, 0) { mstore(add(0xc0, add(ptr, mload(ptr))), 0) // Increment buffer length - 0xc0 plus the original length mstore(ptr, add(0xc0, mload(ptr))) } // If _data is not zero, set size to 0x20 and push to buffer - if iszero(eq(_data, 0)) { // Push data size (0x20) to the end of the buffer mstore(add(0xc0, add(ptr, mload(ptr))), 0x20) // Push data to the end of the buffer mstore(add(0xe0, add(ptr, mload(ptr))), _data) // Increment buffer length - 0xe0 plus the original length mstore(ptr, add(0xe0, mload(ptr))) } // Increment EMITS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of events pushed to buffer - mstore(0x140, add(1, mload(0x140))) } // Update free memory pointer setFreeMem(); } // Begins creating a storage buffer - destinations entered will be forwarded wei // before the end of execution function paying() conditions(validPayBuff, isPaying) internal pure { bytes4 action_req = PAYS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the PAYS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (PAYS) - mstore(0xe0, action_req) // Set the expected next function - PAY_AMT mstore(0x100, 8) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); } // Pushes an amount of wei to forward to the buffer function pay(uint _amount) conditions(validPayAmt, validPayDest) internal pure returns (uint) { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push payment amount to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amount) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - PAY_DEST mstore(0x100, 7) // Increment PAYS action length - mstore( mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) // Update number of payment destinations to be pushed to - mstore(0x160, add(1, mload(0x160))) } // Update free memory pointer setFreeMem(); return _amount; } // Push an address to forward wei to, to the buffer function toAcc(uint, address _dest) conditions(validPayDest, validPayAmt) internal pure { assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push payment destination to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _dest) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - PAY_AMT mstore(0x100, 8) } // Update free memory pointer setFreeMem(); } // Sets the free memory pointer to point beyond all accessed memory function setFreeMem() private pure { assembly { mstore(0x40, msize) } } // Returns the enum representing the next expected function to be called - function expected() private pure returns (NextFunction next) { assembly { next := mload(0x100) } } // Returns the number of events pushed to the storage buffer - function emitted() internal pure returns (uint num_emitted) { if (buffPtr() == bytes32(0)) return 0; // Load number emitted from buffer - assembly { num_emitted := mload(0x140) } } // Returns the number of storage slots pushed to the storage buffer - function stored() internal pure returns (uint num_stored) { if (buffPtr() == bytes32(0)) return 0; // Load number stored from buffer - assembly { num_stored := mload(0x120) } } // Returns the number of payment destinations and amounts pushed to the storage buffer - function paid() internal pure returns (uint num_paid) { if (buffPtr() == bytes32(0)) return 0; // Load number paid from buffer - assembly { num_paid := mload(0x160) } } } library Transfer { using Contract for *; // 'Transfer' event topic signature bytes32 private constant TRANSFER_SIG = keccak256('Transfer(address,address,uint256)'); // Returns the topics for a Transfer event - function TRANSFER (address _owner, address _dest) private pure returns (bytes32[3] memory) { return [TRANSFER_SIG, bytes32(_owner), bytes32(_dest)]; } // Ensures the sender is a transfer agent, or that the tokens are unlocked function canTransfer() internal view { if ( Contract.read(Token.transferAgents(Contract.sender())) == 0 && Contract.read(Token.isFinished()) == 0 ) revert('transfers are locked'); } // Implements the logic for a token transfer - function transfer(address _dest, uint _amt) internal view { // Ensure valid input - if (_dest == 0 || _dest == Contract.sender()) revert('invalid recipient'); // Ensure the sender can currently transfer tokens Contract.checks(canTransfer); // Begin updating balances - Contract.storing(); // Update sender token balance - reverts in case of underflow Contract.decrease(Token.balances(Contract.sender())).by(_amt); // Update recipient token balance - reverts in case of overflow Contract.increase(Token.balances(_dest)).by(_amt); // Finish updating balances: log event - Contract.emitting(); // Log 'Transfer' event Contract.log( TRANSFER(Contract.sender(), _dest), bytes32(_amt) ); } // Implements the logic for a token transferFrom - function transferFrom(address _owner, address _dest, uint _amt) internal view { // Ensure valid input - if (_dest == 0 || _dest == _owner) revert('invalid recipient'); if (_owner == 0) revert('invalid owner'); // Owner must be able to transfer tokens - if ( Contract.read(Token.transferAgents(_owner)) == 0 && Contract.read(Token.isFinished()) == 0 ) revert('transfers are locked'); // Begin updating balances - Contract.storing(); // Update spender token allowance - reverts in case of underflow Contract.decrease(Token.allowed(_owner, Contract.sender())).by(_amt); // Update owner token balance - reverts in case of underflow Contract.decrease(Token.balances(_owner)).by(_amt); // Update recipient token balance - reverts in case of overflow Contract.increase(Token.balances(_dest)).by(_amt); // Finish updating balances: log event - Contract.emitting(); // Log 'Transfer' event Contract.log( TRANSFER(_owner, _dest), bytes32(_amt) ); } } library Approve { using Contract for *; // event Approval(address indexed owner, address indexed spender, uint tokens) bytes32 internal constant APPROVAL_SIG = keccak256('Approval(address,address,uint256)'); // Returns the events and data for an 'Approval' event - function APPROVAL (address _owner, address _spender) private pure returns (bytes32[3] memory) { return [APPROVAL_SIG, bytes32(_owner), bytes32(_spender)]; } // Implements the logic to create the storage buffer for a Token Approval function approve(address _spender, uint _amt) internal pure { // Begin storing values - Contract.storing(); // Store the approved amount at the sender's allowance location for the _spender Contract.set(Token.allowed(Contract.sender(), _spender)).to(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } // Implements the logic to create the storage buffer for a Token Approval function increaseApproval(address _spender, uint _amt) internal view { // Begin storing values - Contract.storing(); // Store the approved amount at the sender's allowance location for the _spender Contract.increase(Token.allowed(Contract.sender(), _spender)).by(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } // Implements the logic to create the storage buffer for a Token Approval function decreaseApproval(address _spender, uint _amt) internal view { // Begin storing values - Contract.storing(); // Decrease the spender's approval by _amt to a minimum of 0 - Contract.decrease(Token.allowed(Contract.sender(), _spender)).byMaximum(_amt); // Finish storing, and begin logging events - Contract.emitting(); // Log 'Approval' event - Contract.log( APPROVAL(Contract.sender(), _spender), bytes32(_amt) ); } } library Token { using Contract for *; /// SALE /// // Whether or not the crowdsale is post-purchase function isFinished() internal pure returns (bytes32) { return keccak256("sale_is_completed"); } /// TOKEN /// // Storage location for token name function tokenName() internal pure returns (bytes32) { return keccak256("token_name"); } // Storage seed for user balances mapping bytes32 internal constant TOKEN_BALANCES = keccak256("token_balances"); function balances(address _owner) internal pure returns (bytes32) { return keccak256(_owner, TOKEN_BALANCES); } // Storage seed for user allowances mapping bytes32 internal constant TOKEN_ALLOWANCES = keccak256("token_allowances"); function allowed(address _owner, address _spender) internal pure returns (bytes32) { return keccak256(_spender, keccak256(_owner, TOKEN_ALLOWANCES)); } // Storage seed for token 'transfer agent' status for any address // Transfer agents can transfer tokens, even if the crowdsale has not yet been finalized bytes32 internal constant TOKEN_TRANSFER_AGENTS = keccak256("token_transfer_agents"); function transferAgents(address _agent) internal pure returns (bytes32) { return keccak256(_agent, TOKEN_TRANSFER_AGENTS); } /// CHECKS /// // Ensures the sale's token has been initialized function tokenInit() internal view { if (Contract.read(tokenName()) == 0) revert('token not initialized'); } // Ensures both storage and events have been pushed to the buffer function emitAndStore() internal pure { if (Contract.emitted() == 0 || Contract.stored() == 0) revert('invalid state change'); } /// FUNCTIONS /// /* Allows a token holder to transfer tokens to another address @param _to: The destination that will recieve tokens @param _amount: The number of tokens to transfer */ function transfer(address _to, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute transfer function - Transfer.transfer(_to, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Allows an approved spender to transfer tokens to another address on an owner's behalf @param _owner: The address from which tokens will be sent @param _recipient: The destination to which tokens will be sent @param _amount: The number of tokens to transfer */ function transferFrom(address _owner, address _recipient, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute transfer function - Transfer.transferFrom(_owner, _recipient, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Approves a spender to spend an amount of your tokens on your behalf @param _spender: The address allowed to spend your tokens @param _amount: The number of tokens that will be approved */ function approve(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.approve(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Increases a spender's approval amount @param _spender: The address allowed to spend your tokens @param _amount: The amount by which the spender's allowance will be increased */ function increaseApproval(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.increaseApproval(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } /* Decreases a spender's approval amount @param _spender: The address allowed to spend your tokens @param _amount: The amount by which the spender's allowance will be decreased */ function decreaseApproval(address _spender, uint _amount) external view { // Begin execution - reads execution id and original sender address from storage Contract.authorize(msg.sender); // Check that the token is initialized - Contract.checks(tokenInit); // Execute approval function - Approve.decreaseApproval(_spender, _amount); // Ensures state change will affect storage and events - Contract.checks(emitAndStore); // Commit state changes to storage - Contract.commit(); } }
Get pointer to buffer length - Push 2 to the end of the buffer - event will have 2 topics Push topics to end of buffer If _data is zero, set data size to 0 in buffer and push - Increment buffer length - 0x80 plus the original length If _data is not zero, set size to 0x20 and push to buffer - Push data size (0x20) to the end of the buffer Push data to the end of the buffer Increment buffer length - 0xa0 plus the original length
function log(bytes32[2] memory _topics, bytes32 _data) conditions(validEvent, validEvent) internal pure { assembly { let ptr := add(0x20, mload(0xc0)) mstore(add(0x20, add(ptr, mload(ptr))), 2) mstore(add(0x40, add(ptr, mload(ptr))), mload(_topics)) mstore(add(0x60, add(ptr, mload(ptr))), mload(add(0x20, _topics))) if eq(_data, 0) { mstore(add(0x80, add(ptr, mload(ptr))), 0) mstore(ptr, add(0x80, mload(ptr))) } if iszero(eq(_data, 0)) { mstore(add(0x80, add(ptr, mload(ptr))), 0x20) mstore(add(0xa0, add(ptr, mload(ptr))), _data) mstore(ptr, add(0xa0, mload(ptr))) } mload(sub(ptr, 0x20)), add(1, mload(mload(sub(ptr, 0x20)))) ) } }
1,484,901
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns 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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./interfaces/ISharks.sol"; import "./interfaces/ICoral.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/IChum.sol"; import "./interfaces/IRandomizer.sol"; contract Sharks is ISharks, ERC721Enumerable, Ownable, Pausable { struct LastWrite { uint64 time; uint64 blockNum; } event TokenMinted(uint256 indexed tokenId, ISharks.SGTokenType indexed tokenType); event TokenStolen(uint256 indexed tokenId, ISharks.SGTokenType indexed tokenType); // max number of tokens that can be minted: 30000 in production uint16 public maxTokens; // number of tokens that can be claimed for a fee: 5,000 uint16 public PAID_TOKENS; // number of tokens have been minted so far uint16 public override minted; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => SGToken) private tokenTraits; // Tracks the last block and timestamp that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => LastWrite) private lastWriteAddress; mapping(uint256 => LastWrite) private lastWriteToken; // count of traits for each type // 0 - 1 are minnows, 2 - 3 are sharks, 4 - 5 are orcas uint8[6] public traitCounts; // reference to the Tower contract to allow transfers to it without approval ICoral public coral; // reference to Traits ITraits public traits; // reference to Randomizer IRandomizer public randomizer; // address => allowedToCallFunctions mapping(address => bool) private admins; constructor(uint16 _maxTokens) ERC721("Shark Game", "SHRK") { maxTokens = _maxTokens; PAID_TOKENS = _maxTokens / 6; _pause(); // Minnows // body traitCounts[0] = 3; // accessory traitCounts[1] = 23; // Sharks // body traitCounts[2] = 3; // accessory traitCounts[3] = 23; // Orcas // body traitCounts[4] = 3; // accessory traitCounts[5] = 23; } /** CRITICAL TO SETUP / MODIFIERS */ modifier requireContractsSet() { require(address(traits) != address(0) && address(coral) != address(0) && address(randomizer) != address(0), "Contracts not set"); _; } modifier blockIfChangingAddress() { require(admins[_msgSender()] || lastWriteAddress[tx.origin].blockNum < block.number, "hmmmm what doing?"); _; } modifier blockIfChangingToken(uint256 tokenId) { require(admins[_msgSender()] || lastWriteToken[tokenId].blockNum < block.number, "hmmmm what doing?"); _; } function setContracts(address _traits, address _coral, address _rand) external onlyOwner { traits = ITraits(_traits); coral = ICoral(_coral); randomizer = IRandomizer(_rand); } /** EXTERNAL */ function getTokenWriteBlock(uint256 tokenId) external view override returns(uint64) { require(admins[_msgSender()], "Only admins can call this"); return lastWriteToken[tokenId].blockNum; } /** * Mint a token - any payment / game logic should be handled in the game contract. * This will just generate random traits and mint a token to a designated address. */ function mint(address recipient, uint256 seed) external override whenNotPaused { require(admins[_msgSender()], "Only admins can call this"); require(minted + 1 <= maxTokens, "All tokens minted"); minted++; generate(minted, seed); if(tx.origin != recipient && recipient != address(coral)) { emit TokenStolen(minted, this.getTokenType(minted)); } _safeMint(recipient, minted); } /** * Burn a token - any game logic should be handled before this function. */ function burn(uint256 tokenId) external override whenNotPaused { require(admins[_msgSender()], "Only admins can call this"); require(ownerOf(tokenId) == tx.origin, "Oops you don't own that"); _burn(tokenId); } function updateOriginAccess(uint16[] memory tokenIds) external override { require(admins[_msgSender()], "Only admins can call this"); uint64 blockNum = uint64(block.number); uint64 time = uint64(block.timestamp); lastWriteAddress[tx.origin] = LastWrite(time, blockNum); for (uint256 i = 0; i < tokenIds.length; i++) { lastWriteToken[tokenIds[i]] = LastWrite(time, blockNum); } } function transferFrom( address from, address to, uint256 tokenId ) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) { // allow admin contracts to be send without approval if(!admins[_msgSender()]) { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); } _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed) internal returns (SGToken memory t) { t = selectTraits(seed); tokenTraits[tokenId] = t; emit TokenMinted(tokenId, this.getTokenType(minted)); } /** * chooses a random trait * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { return uint8(seed) % traitCounts[traitType]; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (SGToken memory t) { bool orcasEnabled = minted > 5000; uint256 typePercent = (seed & 0xFFFF) % 100; t.tokenType = typePercent < 90 ? ISharks.SGTokenType.MINNOW : typePercent < 92 && orcasEnabled ? ISharks.SGTokenType.ORCA : ISharks.SGTokenType.SHARK; uint8 shift = uint8(t.tokenType) * 2; seed >>= 16; t.base = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.accessory = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; } /** READ */ /** * checks if a token is a Wizards * @param tokenId the ID of the token to check * @return wizard - whether or not a token is a Wizards */ function getTokenType(uint256 tokenId) external view override blockIfChangingToken(tokenId) returns (ISharks.SGTokenType) { // Sneaky dragons will be slain if they try to peep this after mint. Nice try. ISharks.SGToken memory s = tokenTraits[tokenId]; return s.tokenType; } function getMaxTokens() external view override returns (uint16) { return maxTokens; } function getPaidTokens() external view override returns (uint16) { return PAID_TOKENS; } /** ADMIN */ /** * updates the number of tokens for sale */ function setPaidTokens(uint16 _paidTokens) external onlyOwner { PAID_TOKENS = _paidTokens; } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disable */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } /** Traits */ function getTokenTraits(uint256 tokenId) external view override blockIfChangingAddress blockIfChangingToken(tokenId) returns (SGToken memory) { return tokenTraits[tokenId]; } function tokenURI(uint256 tokenId) public view override(ERC721, ISharks) blockIfChangingAddress blockIfChangingToken(tokenId) returns (string memory) { require(_exists(tokenId), "Token ID does not exist"); return traits.tokenURI(tokenId); } /** OVERRIDES FOR SAFETY */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override(ERC721Enumerable, IERC721Enumerable) blockIfChangingAddress returns (uint256) { // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWriteAddress[owner].blockNum < block.number, "hmmmm what doing?"); uint256 tokenId = super.tokenOfOwnerByIndex(owner, index); require(admins[_msgSender()] || lastWriteToken[tokenId].blockNum < block.number, "hmmmm what doing?"); return tokenId; } function balanceOf(address owner) public view virtual override(ERC721, IERC721) blockIfChangingAddress returns (uint256) { // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWriteAddress[owner].blockNum < block.number, "hmmmm what doing?"); return super.balanceOf(owner); } function ownerOf(uint256 tokenId) public view virtual override(ERC721, IERC721) blockIfChangingAddress blockIfChangingToken(tokenId) returns (address) { address addr = super.ownerOf(tokenId); // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWriteAddress[addr].blockNum < block.number, "hmmmm what doing?"); return addr; } function tokenByIndex(uint256 index) public view virtual override(ERC721Enumerable, IERC721Enumerable) returns (uint256) { uint256 tokenId = super.tokenByIndex(index); // NICE TRY TOAD DRAGON require(admins[_msgSender()] || lastWriteToken[tokenId].blockNum < block.number, "hmmmm what doing?"); return tokenId; } function approve(address to, uint256 tokenId) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) { super.approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) returns (address) { return super.getApproved(tokenId); } function setApprovalForAll(address operator, bool approved) public virtual override(ERC721, IERC721) blockIfChangingAddress { super.setApprovalForAll(operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override(ERC721, IERC721) blockIfChangingAddress returns (bool) { return super.isApprovedForAll(owner, operator); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) { super.safeTransferFrom(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override(ERC721, IERC721) blockIfChangingToken(tokenId) { super.safeTransferFrom(from, to, tokenId, _data); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IChum { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function updateOriginAccess() external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "./ISharks.sol"; interface ICoral { function addManyToCoral(address account, uint16[] calldata tokenIds) external; function randomTokenOwner(ISharks.SGTokenType tokenType, uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IRandomizer { function random() external returns (uint256); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface ISharks is IERC721Enumerable { // game data storage enum SGTokenType { MINNOW, SHARK, ORCA } struct SGToken { SGTokenType tokenType; uint8 base; uint8 accessory; } function minted() external returns (uint16); function updateOriginAccess(uint16[] memory tokenIds) external; function mint(address recipient, uint256 seed) external; function burn(uint256 tokenId) external; function getMaxTokens() external view returns (uint16); function getPaidTokens() external view returns (uint16); function tokenURI(uint256 tokenId) external view returns (string memory); function getTokenTraits(uint256 tokenId) external view returns (SGToken memory); function getTokenWriteBlock(uint256 tokenId) external view returns(uint64); function getTokenType(uint256 tokenId) external view returns(SGTokenType); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); }
Y U checking on this address in the same block it's being modified... hmmmm
function balanceOf(address owner) public view virtual override(ERC721, IERC721) blockIfChangingAddress returns (uint256) { require(admins[_msgSender()] || lastWriteAddress[owner].blockNum < block.number, "hmmmm what doing?"); return super.balanceOf(owner); }
10,272,849
pragma solidity ^0.4.24; contract WeatherC1 { struct WeatherData { uint date; string temperature; string humidity; } //Array with all WeatherData WeatherData[] private entityStructs; modifier checkLength { require(entityStructs.length != 0); _; } //Creates a new struct and adds it to the array. date as integer because of unix timestamp //temperature and humidity as string because of missing float in solidity function createEntity(uint date, string temperature, string humidity) public { WeatherData memory newEntity; newEntity.date = date; newEntity.temperature = temperature; newEntity.humidity = humidity; entityStructs.push(newEntity); } //Returns the length of the array function getEntityCount() public constant returns(uint entityCount) { return entityStructs.length; } //Returns one Temperature entry function getTemperatureByNumber(uint nr) public constant returns(string){ return entityStructs[nr].temperature; } //Returns one Humidity entry function getHumidityByNumber(uint nr) public constant returns(string){ return entityStructs[nr].humidity; } //Returns a full struct out of the array function getAllByNumber(uint nr) public constant returns(uint, string, string){ return(entityStructs[nr].date, entityStructs[nr].temperature, entityStructs[nr].humidity); } //Returns allways the last entry in the array function getLastEntry() public constant checkLength returns(uint, string, string){ uint nr = entityStructs.length - 1; return(entityStructs[nr].date, entityStructs[nr].temperature, entityStructs[nr].humidity); } }
Returns one Temperature entry
function getTemperatureByNumber(uint nr) public constant returns(string){ return entityStructs[nr].temperature; }
2,564,737
pragma solidity ^0.8.2; import {VaultAPI, BaseWrapper, RegistryAPI} from "./wrapper/BaseWrapper.sol"; import {ApeVaultFactory} from "./wrapper/ApeVaultFactory.sol"; import {ApeVaultWrapper} from "./wrapper/ApeVault.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract ApeRouter is Ownable { using SafeERC20 for IERC20; uint256 constant MAX_UINT = type(uint256).max; address public yearnRegistry; address public apeVaultFactory; constructor(address _reg, address _factory) { yearnRegistry = _reg; apeVaultFactory = _factory; } event DepositInVault(address indexed vault, address token, uint256 amount); function delegateDeposit(address _apeVault, address _token, uint256 _amount) external returns(uint256 deposited) { VaultAPI vault = VaultAPI(RegistryAPI(yearnRegistry).latestVault(_token)); require(address(vault) != address(0), "ApeRouter: No vault for token"); require(ApeVaultFactory(apeVaultFactory).vaultRegistry(_apeVault), "ApeRouter: Vault does not exist"); require(address(vault) == address(ApeVaultWrapper(_apeVault).vault()), "ApeRouter: yearn Vault not identical"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); if (IERC20(_token).allowance(address(this), address(vault)) < _amount) { IERC20(_token).safeApprove(address(vault), 0); // Avoid issues with some IERC20(_token)s requiring 0 IERC20(_token).safeApprove(address(vault), MAX_UINT); // Vaults are trusted } uint256 beforeBal = IERC20(_token).balanceOf(address(this)); uint256 sharesMinted = vault.deposit(_amount, _apeVault); uint256 afterBal = IERC20(_token).balanceOf(address(this)); deposited = beforeBal - afterBal; // `receiver` now has shares of `_bestVault` as balance, converted to `token` here // Issue a refund if not everything was deposited // adding protocol removal call //if (afterBal > 0) IERC20(_token).safeTransfer(msg.sender, afterBal); ApeVaultWrapper(_apeVault).addFunds(deposited); emit DepositInVault(_apeVault, _token, sharesMinted); } function removeTokens(address _token) external onlyOwner { IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this))); } /** * @notice * Used to update the yearn registry. * @param _registry The new _registry address. */ function setRegistry(address _registry) external onlyOwner { //require(msg.sender == RegistryAPI(yearnRegistry).governance()); // In case you want to override the registry instead of re-deploying yearnRegistry = _registry; // Make sure there's no change in governance // NOTE: Also avoid bricking the wrapper from setting a bad registry //require(msg.sender == RegistryAPI(yearnRegistry).governance()); } }
Used to update the yearn registry. _registry The new _registry address./require(msg.sender == RegistryAPI(yearnRegistry).governance()); In case you want to override the registry instead of re-deploying Make sure there's no change in governance NOTE: Also avoid bricking the wrapper from setting a bad registryrequire(msg.sender == RegistryAPI(yearnRegistry).governance());
function setRegistry(address _registry) external onlyOwner { yearnRegistry = _registry; }
7,325,734
pragma solidity ^0.8.0; import "./WalletRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@gnosis.pm/safe-contracts/contracts/GnosisSafe.sol"; import "@gnosis.pm/safe-contracts/contracts/proxies/IProxyCreationCallback.sol"; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "hardhat/console.sol"; contract AaronPwn { constructor() { } receive() payable external {} fallback() external payable {} function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { console.log("bruh from AaronPwn"); } function test(address addy) external { console.log("NO FRICKIN WAY WE got to test(%s) via %s", addy, address(this)); address(this).call(abi.encodeWithSignature("enableModule(address)", addy)); } function execTransaction(address addy, address to, uint256 value, bytes memory data) public { //addy.call(abi.encodeWithSignature("execTransactionFromModule(address,uint256,bytes memory,Enum.Operation)", to, value, data, Enum.Operation.Call)); ModuleManager mm = ModuleManager(addy); mm.execTransactionFromModule(to, value, data, Enum.Operation.Call); console.log("kk done with exec txn"); } function becomeOwner(address addy, address currentOwner) external { execTransaction(addy, addy, 0, abi.encodeWithSignature( "swapOwner(address,address,address)", address(0x1), currentOwner, msg.sender ) ); } function getWallet(address _registry, address owner) public returns (address) { WalletRegistry registry = WalletRegistry(_registry); return registry.wallets(owner); } function stealMoney(address registry, address owner, address token) public { console.log("lmao u really trusted dEcEnTrAlIzAtIoN with ur $$"); bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", msg.sender, 10 ether); //require(manager.execTransactionFromModule(token, 0, data, Enum.Operation.Call), "Could not execute token transfer"); address owner = getWallet(registry, owner); console.log("stealMoney: OWNER: %s", owner); execTransaction(owner, token, 0, data); } }
addy.call(abi.encodeWithSignature("execTransactionFromModule(address,uint256,bytes memory,Enum.Operation)", to, value, data, Enum.Operation.Call));
function execTransaction(address addy, address to, uint256 value, bytes memory data) public { ModuleManager mm = ModuleManager(addy); mm.execTransactionFromModule(to, value, data, Enum.Operation.Call); console.log("kk done with exec txn"); }
5,419,593
./full_match/43114/0xa0186686f1A201dca8DAd8f3174c5298d3121e7D/sources/contracts/TestAvax.sol
Locks the contract for janitor for the amount of time provided
function lockJanitor(uint256 time) public virtual onlyJanitor {
4,517,029
./full_match/80001/0x5aC586Ecad7dEb8E593c4279d445842A9461D69A/sources/contracts/KOMPrivateSale.sol
msg.sender.transfer(amount); Transfer amount USDT tokens from msg.sender to contractdai.transferFrom(msg.sender, address(this), _amount); Send amount tokens to msg.sender token.transfer(msg.sender, amount);
function despoitUSDT(uint256 _amount) external{ uint256 allowance = dai.allowance(msg.sender, address(this)); require(allowance >= _amount, "Check the token allowance"); dai.transferFrom(msg.sender, address(this), _amount); }
5,694,759
/** *Submitted for verification at Etherscan.io on 2021-11-30 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IBaseFee interface IBaseFee { function isCurrentBaseFeeAcceptable() external view returns (bool); } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // EURt uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // Compound, sAave uint256[2] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // Iron Bank, Aave uint256[3] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3Crv Metapools address pool, uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // Y and yBUSD uint256[4] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3pool uint256[3] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // sUSD uint256[4] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); // EURt function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3Crv Metapools function calc_token_amount( address _pool, uint256[4] calldata _amounts, bool _is_deposit ) external view returns (uint256); // sUSD, Y pool, etc function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3pool, Iron Bank, etc function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 amount, int128 i) external view returns (uint256); } // Part: ICurveStrategyProxy interface ICurveStrategyProxy { function proxy() external returns (address); function balanceOf(address _gauge) external view returns (uint256); function deposit(address _gauge, address _token) external; function withdraw( address _gauge, address _token, uint256 _amount ) external returns (uint256); function withdrawAll(address _gauge, address _token) external returns (uint256); function harvest(address _gauge) external; function lock() external; function approveStrategy(address) external; function revokeStrategy(address) external; function claimRewards(address _gauge, address _token) external; } // Part: IUniV3 interface IUniV3 { struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // 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) { // 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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: StrategyCurveBase abstract contract StrategyCurveBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // these should stay the same across different wants. // curve infrastructure contracts ICurveStrategyProxy public proxy; // Below we set it to Yearn's Updated v4 StrategyProxy address public gauge; // Curve gauge contract, most are tokenized, held by Yearn's voter // keepCRV stuff uint256 public keepCRV = 1000; // the percentage of CRV we re-lock for boost (in basis points) uint256 internal constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in basis points address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter // Swap stuff address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV and CVX liquidity there IERC20 internal constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 internal constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us string internal stratName; // set our strategy name here /* ========== CONSTRUCTOR ========== */ constructor(address _vault) public BaseStrategy(_vault) {} /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return stratName; } function stakedBalance() public view returns (uint256) { return proxy.balanceOf(gauge); } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(stakedBalance()); } /* ========== MUTATIVE FUNCTIONS ========== */ // these should stay the same across different wants. function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } // Send all of our LP tokens to the proxy and deposit to the gauge if we have any uint256 _toInvest = balanceOfWant(); if (_toInvest > 0) { want.safeTransfer(address(proxy), _toInvest); proxy.deposit(gauge, address(want)); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _wantBal = balanceOfWant(); if (_amountNeeded > _wantBal) { // check if we have enough free funds to cover the withdrawal uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _amountNeeded.sub(_wantBal)) ); } uint256 _withdrawnBal = balanceOfWant(); _liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal); _loss = _amountNeeded.sub(_liquidatedAmount); } else { // we have enough balance to cover the liquidation available return (_amountNeeded, 0); } } // fire sale, get rid of it all! function liquidateAllPositions() internal override returns (uint256) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { // don't bother withdrawing zero proxy.withdraw(gauge, address(want), _stakedBal); } return balanceOfWant(); } function prepareMigration(address _newStrategy) internal override { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.withdraw(gauge, address(want), _stakedBal); } } function protectedTokens() internal view override returns (address[] memory) {} /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Use to update Yearn's StrategyProxy contract as needed in case of upgrades. function setProxy(address _proxy) external onlyGovernance { proxy = ICurveStrategyProxy(_proxy); } // Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%. function setKeepCRV(uint256 _keepCRV) external onlyAuthorized { require(_keepCRV <= 10_000); keepCRV = _keepCRV; } // This allows us to manually harvest with our keeper as needed function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce) external onlyAuthorized { forceHarvestTriggerOnce = _forceHarvestTriggerOnce; } } // File: StrategyCurve3CrvRewardsClonable.sol contract StrategyCurve3CrvRewardsClonable is StrategyCurveBase { /* ========== STATE VARIABLES ========== */ // these will likely change across different wants. // Curve stuff address public curve; // This is our pool specific to this vault. Use it with zap contract to specify our correct pool. ICurveFi internal constant zapContract = ICurveFi(0xA79828DF1850E8a3A3064576f380D90aECDD3359); // this is used for depositing to all 3Crv metapools // we use these to deposit to our curve pool address public targetStable; address internal constant uniswapv3 = address(0xE592427A0AEce92De3Edee1F18E0157C05861564); IERC20 internal constant usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 internal constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 internal constant dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); uint24 public uniCrvFee; // this is equal to 1%, can change this later if a different path becomes more optimal uint24 public uniStableFee; // this is equal to 0.05%, can change this later if a different path becomes more optimal // rewards token info. we can have more than 1 reward token but this is rare, so we don't include this in the template IERC20 public rewardsToken; bool public hasRewards; address[] internal rewardsPath; // check for cloning bool internal isOriginal = true; /* ========== CONSTRUCTOR ========== */ constructor( address _vault, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) public StrategyCurveBase(_vault) { _initializeStrat(_curvePool, _gauge, _hasRewards, _rewardsToken, _name); } /* ========== CLONING ========== */ event Cloned(address indexed clone); // we use this to clone our original strategy to other vaults function cloneCurve3CrvRewards( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) external returns (address newStrategy) { require(isOriginal); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyCurve3CrvRewardsClonable(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _curvePool, _gauge, _hasRewards, _rewardsToken, _name ); emit Cloned(newStrategy); } // this will only be called by the clone function above function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) public { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_curvePool, _gauge, _hasRewards, _rewardsToken, _name); } // this is called by our original strategy, as well as any clones function _initializeStrat( address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) internal { // make sure that we haven't initialized this before require(address(curve) == address(0)); // already initialized. // You can set these parameters on deployment to whatever you want maxReportDelay = 7 days; // 7 days in seconds minReportDelay = 3 days; // 3 days in seconds healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth // need to set our proxy again when cloning since it's not a constant proxy = ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152); // these are our standard approvals. want = Curve LP token want.approve(address(proxy), type(uint256).max); crv.approve(uniswapv3, type(uint256).max); weth.approve(uniswapv3, type(uint256).max); // set our keepCRV keepCRV = 1000; // setup our rewards if we have them if (_hasRewards) { rewardsToken = IERC20(_rewardsToken); rewardsToken.approve(sushiswap, type(uint256).max); rewardsPath = [address(rewardsToken), address(weth), address(dai)]; hasRewards = true; } // this is the pool specific to this vault, but we only use it as an address curve = address(_curvePool); // set our curve gauge contract gauge = address(_gauge); // set our strategy's name stratName = _name; // these are our approvals and path specific to this contract dai.approve(address(zapContract), type(uint256).max); usdt.safeApprove(address(zapContract), type(uint256).max); // USDT requires safeApprove(), funky token usdc.approve(address(zapContract), type(uint256).max); // start with dai targetStable = address(dai); // set our uniswap pool fees uniCrvFee = 10000; uniStableFee = 500; } /* ========== MUTATIVE FUNCTIONS ========== */ // these will likely change across different wants. function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // if we have anything in the gauge, then harvest CRV from the gauge uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.harvest(gauge); uint256 _crvBalance = crv.balanceOf(address(this)); // if we claimed any CRV, then sell it if (_crvBalance > 0) { // keep some of our CRV to increase our boost uint256 _sendToVoter = _crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (keepCRV > 0) { crv.safeTransfer(voter, _sendToVoter); } uint256 crvRemainder = _crvBalance.sub(_sendToVoter); if (hasRewards) { proxy.claimRewards(gauge, address(rewardsToken)); uint256 _rewardsBalance = rewardsToken.balanceOf(address(this)); if (_rewardsBalance > 0) { _sellRewards(_rewardsBalance); } } if (crvRemainder > 0) { _sell(crvRemainder); } // check for balances of tokens to deposit uint256 _daiBalance = dai.balanceOf(address(this)); uint256 _usdcBalance = usdc.balanceOf(address(this)); uint256 _usdtBalance = usdt.balanceOf(address(this)); // deposit our balance to Curve if we have any if (_daiBalance > 0 || _usdcBalance > 0 || _usdtBalance > 0) { zapContract.add_liquidity( curve, [0, _daiBalance, _usdcBalance, _usdtBalance], 0 ); } } } // debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio if (_debtOutstanding > 0) { if (_stakedBal > 0) { // don't bother withdrawing if we don't have staked funds proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } // serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { // this should only be hit following donations to strategy liquidateAllPositions(); } } // if assets are less than debt, we are in trouble else { _loss = debt.sub(assets); } // we're done harvesting, so reset our trigger if we used it forceHarvestTriggerOnce = false; } // Sells our harvested CRV into the selected output. function _sell(uint256 _amount) internal { IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(crv), uint24(uniCrvFee), address(weth) ), address(this), block.timestamp, _amount, uint256(1) ) ); uint256 _wethBalance = weth.balanceOf(address(this)); IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(weth), uint24(uniStableFee), address(targetStable) ), address(this), block.timestamp, _wethBalance, uint256(1) ) ); } // Sells our harvested reward token into the selected output. function _sellRewards(uint256 _amount) internal { IUniswapV2Router02(sushiswap).swapExactTokensForTokens( _amount, uint256(0), rewardsPath, address(this), block.timestamp ); } /* ========== KEEP3RS ========== */ function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // harvest no matter what once we reach our maxDelay if (block.timestamp.sub(params.lastReport) > maxReportDelay) { return true; } // check if the base fee gas price is higher than we allow. if it is, block harvests. if (!isBaseFeeAcceptable()) { return false; } // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // harvest if we hit our minDelay, but only if our gas price is acceptable if (block.timestamp.sub(params.lastReport) > minReportDelay) { return true; } // otherwise, we don't harvest return false; } // convert our keeper's eth cost into want, we don't need this anymore since we don't use baseStrategy harvestTrigger function ethToWant(uint256 _ethAmount) public view override returns (uint256) { return _ethAmount; } // check if the current baseFee is below our external target function isBaseFeeAcceptable() internal view returns (bool) { return IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F) .isCurrentBaseFeeAcceptable(); } /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Use to add or update rewards function updateRewards(address _rewardsToken) external onlyGovernance { // reset allowance to zero for our previous token if we had one if (address(rewardsToken) != address(0)) { rewardsToken.approve(sushiswap, uint256(0)); } // update with our new token, use dai as default rewardsToken = IERC20(_rewardsToken); rewardsToken.approve(sushiswap, type(uint256).max); rewardsPath = [address(rewardsToken), address(weth), address(dai)]; hasRewards = true; } // Use to turn off extra rewards claiming function turnOffRewards() external onlyGovernance { hasRewards = false; if (address(rewardsToken) != address(0)) { rewardsToken.approve(sushiswap, uint256(0)); } rewardsToken = IERC20(address(0)); } // Set optimal token to sell harvested funds for depositing to Curve. // Default is DAI, but can be set to USDC or USDT as needed by strategist or governance. function setOptimal(uint256 _optimal) external onlyAuthorized { if (_optimal == 0) { targetStable = address(dai); } else if (_optimal == 1) { targetStable = address(usdc); } else if (_optimal == 2) { targetStable = address(usdt); } else { revert("incorrect token"); } } // set the fee pool we'd like to swap through for CRV on UniV3 (1% = 10_000) function setUniFees(uint24 _crvFee, uint24 _stableFee) external onlyAuthorized { uniCrvFee = _crvFee; uniStableFee = _stableFee; } }
Set optimal token to sell harvested funds for depositing to Curve. Default is DAI, but can be set to USDC or USDT as needed by strategist or governance.
function setOptimal(uint256 _optimal) external onlyAuthorized { if (_optimal == 0) { targetStable = address(dai); targetStable = address(usdc); targetStable = address(usdt); revert("incorrect token"); } }
2,340,357
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 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 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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @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&#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; } } library MathUtils { using SafeMath for uint256; // Divisor used for representing percentages uint256 public constant PERC_DIVISOR = 1000000; /* * @dev Returns whether an amount is a valid percentage out of PERC_DIVISOR * @param _amount Amount that is supposed to be a percentage */ function validPerc(uint256 _amount) internal pure returns (bool) { return _amount <= PERC_DIVISOR; } /* * @dev Compute percentage of a value with the percentage represented by a fraction * @param _amount Amount to take the percentage of * @param _fracNum Numerator of fraction representing the percentage * @param _fracDenom Denominator of fraction representing the percentage */ function percOf(uint256 _amount, uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) { return _amount.mul(percPoints(_fracNum, _fracDenom)).div(PERC_DIVISOR); } /* * @dev Compute percentage of a value with the percentage represented by a fraction over PERC_DIVISOR * @param _amount Amount to take the percentage of * @param _fracNum Numerator of fraction representing the percentage with PERC_DIVISOR as the denominator */ function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) { return _amount.mul(_fracNum).div(PERC_DIVISOR); } /* * @dev Compute percentage representation of a fraction * @param _fracNum Numerator of fraction represeting the percentage * @param _fracDenom Denominator of fraction represeting the percentage */ function percPoints(uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) { return _fracNum.mul(PERC_DIVISOR).div(_fracDenom); } } contract IController is Pausable { event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash); function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external; function updateController(bytes32 _id, address _controller) external; function getContract(bytes32 _id) public view returns (address); } contract IManager { event SetController(address controller); event ParameterUpdate(string param); function setController(address _controller) external; } contract Manager is IManager { // Controller that contract is registered with IController public controller; // Check if sender is controller modifier onlyController() { require(msg.sender == address(controller)); _; } // Check if sender is controller owner modifier onlyControllerOwner() { require(msg.sender == controller.owner()); _; } // Check if controller is not paused modifier whenSystemNotPaused() { require(!controller.paused()); _; } // Check if controller is paused modifier whenSystemPaused() { require(controller.paused()); _; } function Manager(address _controller) public { controller = IController(_controller); } /* * @dev Set controller. Only callable by current controller * @param _controller Controller contract address */ function setController(address _controller) external onlyController { controller = IController(_controller); SetController(_controller); } } /** * @title ManagerProxyTarget * @dev The base contract that target contracts used by a proxy contract should inherit from * Note: Both the target contract and the proxy contract (implemented as ManagerProxy) MUST inherit from ManagerProxyTarget in order to guarantee * that both contracts have the same storage layout. Differing storage layouts in a proxy contract and target contract can * potentially break the delegate proxy upgradeability mechanism */ contract ManagerProxyTarget is Manager { // Used to look up target contract address in controller&#39;s registry bytes32 public targetContractId; } /* * @title A sorted doubly linked list with nodes sorted in descending order. Optionally accepts insert position hints * * Given a new node with a `key`, a hint is of the form `(prevId, nextId)` s.t. `prevId` and `nextId` are adjacent in the list. * `prevId` is a node with a key >= `key` and `nextId` is a node with a key <= `key`. If the sender provides a hint that is a valid insert position * the insert operation is a constant time storage write. However, the provided hint in a given transaction might be a valid insert position, but if other transactions are included first, when * the given transaction is executed the provided hint may no longer be a valid insert position. For example, one of the nodes referenced might be removed or their keys may * be updated such that the the pair of nodes in the hint no longer represent a valid insert position. If one of the nodes in the hint becomes invalid, we still try to use the other * valid node as a starting point for finding the appropriate insert position. If both nodes in the hint become invalid, we use the head of the list as a starting point * to find the appropriate insert position. */ library SortedDoublyLL { using SafeMath for uint256; // Information for a node in the list struct Node { uint256 key; // Node&#39;s key used for sorting address nextId; // Id of next node (smaller key) in the list address prevId; // Id of previous node (larger key) in the list } // Information for the list struct Data { address head; // Head of the list. Also the node in the list with the largest key address tail; // Tail of the list. Also the node in the list with the smallest key uint256 maxSize; // Maximum size of the list uint256 size; // Current size of the list mapping (address => Node) nodes; // Track the corresponding ids for each node in the list } /* * @dev Set the maximum size of the list * @param _size Maximum size */ function setMaxSize(Data storage self, uint256 _size) public { // New max size must be greater than old max size require(_size > self.maxSize); self.maxSize = _size; } /* * @dev Add a node to the list * @param _id Node&#39;s id * @param _key Node&#39;s key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function insert(Data storage self, address _id, uint256 _key, address _prevId, address _nextId) public { // List must not be full require(!isFull(self)); // List must not already contain node require(!contains(self, _id)); // Node id must not be null require(_id != address(0)); // Key must be non-zero require(_key > 0); address prevId = _prevId; address nextId = _nextId; if (!validInsertPosition(self, _key, prevId, nextId)) { // Sender&#39;s hint was not a valid insert position // Use sender&#39;s hint to find a valid insert position (prevId, nextId) = findInsertPosition(self, _key, prevId, nextId); } self.nodes[_id].key = _key; if (prevId == address(0) && nextId == address(0)) { // Insert as head and tail self.head = _id; self.tail = _id; } else if (prevId == address(0)) { // Insert before `prevId` as the head self.nodes[_id].nextId = self.head; self.nodes[self.head].prevId = _id; self.head = _id; } else if (nextId == address(0)) { // Insert after `nextId` as the tail self.nodes[_id].prevId = self.tail; self.nodes[self.tail].nextId = _id; self.tail = _id; } else { // Insert at insert position between `prevId` and `nextId` self.nodes[_id].nextId = nextId; self.nodes[_id].prevId = prevId; self.nodes[prevId].nextId = _id; self.nodes[nextId].prevId = _id; } self.size = self.size.add(1); } /* * @dev Remove a node from the list * @param _id Node&#39;s id */ function remove(Data storage self, address _id) public { // List must contain the node require(contains(self, _id)); if (self.size > 1) { // List contains more than a single node if (_id == self.head) { // The removed node is the head // Set head to next node self.head = self.nodes[_id].nextId; // Set prev pointer of new head to null self.nodes[self.head].prevId = address(0); } else if (_id == self.tail) { // The removed node is the tail // Set tail to previous node self.tail = self.nodes[_id].prevId; // Set next pointer of new tail to null self.nodes[self.tail].nextId = address(0); } else { // The removed node is neither the head nor the tail // Set next pointer of previous node to the next node self.nodes[self.nodes[_id].prevId].nextId = self.nodes[_id].nextId; // Set prev pointer of next node to the previous node self.nodes[self.nodes[_id].nextId].prevId = self.nodes[_id].prevId; } } else { // List contains a single node // Set the head and tail to null self.head = address(0); self.tail = address(0); } delete self.nodes[_id]; self.size = self.size.sub(1); } /* * @dev Update the key of a node in the list * @param _id Node&#39;s id * @param _newKey Node&#39;s new key * @param _prevId Id of previous node for the new insert position * @param _nextId Id of next node for the new insert position */ function updateKey(Data storage self, address _id, uint256 _newKey, address _prevId, address _nextId) public { // List must contain the node require(contains(self, _id)); // Remove node from the list remove(self, _id); if (_newKey > 0) { // Insert node if it has a non-zero key insert(self, _id, _newKey, _prevId, _nextId); } } /* * @dev Checks if the list contains a node * @param _transcoder Address of transcoder */ function contains(Data storage self, address _id) public view returns (bool) { // List only contains non-zero keys, so if key is non-zero the node exists return self.nodes[_id].key > 0; } /* * @dev Checks if the list is full */ function isFull(Data storage self) public view returns (bool) { return self.size == self.maxSize; } /* * @dev Checks if the list is empty */ function isEmpty(Data storage self) public view returns (bool) { return self.size == 0; } /* * @dev Returns the current size of the list */ function getSize(Data storage self) public view returns (uint256) { return self.size; } /* * @dev Returns the maximum size of the list */ function getMaxSize(Data storage self) public view returns (uint256) { return self.maxSize; } /* * @dev Returns the key of a node in the list * @param _id Node&#39;s id */ function getKey(Data storage self, address _id) public view returns (uint256) { return self.nodes[_id].key; } /* * @dev Returns the first node in the list (node with the largest key) */ function getFirst(Data storage self) public view returns (address) { return self.head; } /* * @dev Returns the last node in the list (node with the smallest key) */ function getLast(Data storage self) public view returns (address) { return self.tail; } /* * @dev Returns the next node (with a smaller key) in the list for a given node * @param _id Node&#39;s id */ function getNext(Data storage self, address _id) public view returns (address) { return self.nodes[_id].nextId; } /* * @dev Returns the previous node (with a larger key) in the list for a given node * @param _id Node&#39;s id */ function getPrev(Data storage self, address _id) public view returns (address) { return self.nodes[_id].prevId; } /* * @dev Check if a pair of nodes is a valid insertion point for a new node with the given key * @param _key Node&#39;s key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function validInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) public view returns (bool) { if (_prevId == address(0) && _nextId == address(0)) { // `(null, null)` is a valid insert position if the list is empty return isEmpty(self); } else if (_prevId == address(0)) { // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list return self.head == _nextId && _key >= self.nodes[_nextId].key; } else if (_nextId == address(0)) { // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list return self.tail == _prevId && _key <= self.nodes[_prevId].key; } else { // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_key` falls between the two nodes&#39; keys return self.nodes[_prevId].nextId == _nextId && self.nodes[_prevId].key >= _key && _key >= self.nodes[_nextId].key; } } /* * @dev Descend the list (larger keys to smaller keys) to find a valid insert position * @param _key Node&#39;s key * @param _startId Id of node to start ascending the list from */ function descendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the head, check if the insert position is before the head if (self.head == _startId && _key >= self.nodes[_startId].key) { return (address(0), _startId); } address prevId = _startId; address nextId = self.nodes[prevId].nextId; // Descend the list until we reach the end or until we find a valid insert position while (prevId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) { prevId = self.nodes[prevId].nextId; nextId = self.nodes[prevId].nextId; } return (prevId, nextId); } /* * @dev Ascend the list (smaller keys to larger keys) to find a valid insert position * @param _key Node&#39;s key * @param _startId Id of node to start descending the list from */ function ascendList(Data storage self, uint256 _key, address _startId) private view returns (address, address) { // If `_startId` is the tail, check if the insert position is after the tail if (self.tail == _startId && _key <= self.nodes[_startId].key) { return (_startId, address(0)); } address nextId = _startId; address prevId = self.nodes[nextId].prevId; // Ascend the list until we reach the end or until we find a valid insertion point while (nextId != address(0) && !validInsertPosition(self, _key, prevId, nextId)) { nextId = self.nodes[nextId].prevId; prevId = self.nodes[nextId].prevId; } return (prevId, nextId); } /* * @dev Find the insert position for a new node with the given key * @param _key Node&#39;s key * @param _prevId Id of previous node for the insert position * @param _nextId Id of next node for the insert position */ function findInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) private view returns (address, address) { address prevId = _prevId; address nextId = _nextId; if (prevId != address(0)) { if (!contains(self, prevId) || _key > self.nodes[prevId].key) { // `prevId` does not exist anymore or now has a smaller key than the given key prevId = address(0); } } if (nextId != address(0)) { if (!contains(self, nextId) || _key < self.nodes[nextId].key) { // `nextId` does not exist anymore or now has a larger key than the given key nextId = address(0); } } if (prevId == address(0) && nextId == address(0)) { // No hint - descend list starting from head return descendList(self, _key, self.head); } else if (prevId == address(0)) { // No `prevId` for hint - ascend list starting from `nextId` return ascendList(self, _key, nextId); } else if (nextId == address(0)) { // No `nextId` for hint - descend list starting from `prevId` return descendList(self, _key, prevId); } else { // Descend list starting from `prevId` return descendList(self, _key, prevId); } } } library EarningsPool { using SafeMath for uint256; // Represents rewards and fees to be distributed to delegators struct Data { uint256 rewardPool; // Rewards in the pool uint256 feePool; // Fees in the pool uint256 totalStake; // Transcoder&#39;s total stake during the pool&#39;s round uint256 claimableStake; // Stake that can be used to claim portions of the fee and reward pool uint256 transcoderRewardCut; // Reward cut for the reward pool uint256 transcoderFeeShare; // Fee share for the fee pool } function init(EarningsPool.Data storage earningsPool, uint256 _stake, uint256 _rewardCut, uint256 _feeShare) internal { earningsPool.totalStake = _stake; earningsPool.claimableStake = _stake; earningsPool.transcoderRewardCut = _rewardCut; earningsPool.transcoderFeeShare = _feeShare; } function hasClaimableShares(EarningsPool.Data storage earningsPool) internal view returns (bool) { return earningsPool.claimableStake > 0; } function claimShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal returns (uint256, uint256) { uint256 fees = 0; uint256 rewards = 0; if (earningsPool.feePool > 0) { // Compute fee share fees = feePoolShare(earningsPool, _stake, _isTranscoder); earningsPool.feePool = earningsPool.feePool.sub(fees); } if (earningsPool.rewardPool > 0) { // Compute reward share rewards = rewardPoolShare(earningsPool, _stake, _isTranscoder); earningsPool.rewardPool = earningsPool.rewardPool.sub(rewards); } // Update remaning claimable stake for token pools earningsPool.claimableStake = earningsPool.claimableStake.sub(_stake); return (fees, rewards); } function feePoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) { uint256 transcoderFees = 0; uint256 delegatorFees = 0; if (earningsPool.claimableStake > 0) { uint256 delegatorsFees = MathUtils.percOf(earningsPool.feePool, earningsPool.transcoderFeeShare); transcoderFees = earningsPool.feePool.sub(delegatorsFees); delegatorFees = MathUtils.percOf(delegatorsFees, _stake, earningsPool.claimableStake); } if (_isTranscoder) { return delegatorFees.add(transcoderFees); } else { return delegatorFees; } } function rewardPoolShare(EarningsPool.Data storage earningsPool, uint256 _stake, bool _isTranscoder) internal view returns (uint256) { uint256 transcoderRewards = 0; uint256 delegatorRewards = 0; if (earningsPool.claimableStake > 0) { transcoderRewards = MathUtils.percOf(earningsPool.rewardPool, earningsPool.transcoderRewardCut); delegatorRewards = MathUtils.percOf(earningsPool.rewardPool.sub(transcoderRewards), _stake, earningsPool.claimableStake); } if (_isTranscoder) { return delegatorRewards.add(transcoderRewards); } else { return delegatorRewards; } } } contract ILivepeerToken is ERC20, Ownable { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _amount) public; } /** * @title Minter interface */ contract IMinter { // Events event SetCurrentRewardTokens(uint256 currentMintableTokens, uint256 currentInflation); // External functions function createReward(uint256 _fracNum, uint256 _fracDenom) external returns (uint256); function trustedTransferTokens(address _to, uint256 _amount) external; function trustedBurnTokens(uint256 _amount) external; function trustedWithdrawETH(address _to, uint256 _amount) external; function depositETH() external payable returns (bool); function setCurrentRewardTokens() external; // Public functions function getController() public view returns (IController); } /** * @title RoundsManager interface */ contract IRoundsManager { // Events event NewRound(uint256 round); // External functions function initializeRound() external; // Public functions function blockNum() public view returns (uint256); function blockHash(uint256 _block) public view returns (bytes32); function currentRound() public view returns (uint256); function currentRoundStartBlock() public view returns (uint256); function currentRoundInitialized() public view returns (bool); function currentRoundLocked() public view returns (bool); } /* * @title Interface for BondingManager */ contract IBondingManager { event TranscoderUpdate(address indexed transcoder, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment, bool registered); event TranscoderEvicted(address indexed transcoder); event TranscoderResigned(address indexed transcoder); event TranscoderSlashed(address indexed transcoder, address finder, uint256 penalty, uint256 finderReward); event Reward(address indexed transcoder, uint256 amount); event Bond(address indexed delegate, address indexed delegator); event Unbond(address indexed delegate, address indexed delegator); event WithdrawStake(address indexed delegator); event WithdrawFees(address indexed delegator); // External functions function setActiveTranscoders() external; function updateTranscoderWithFees(address _transcoder, uint256 _fees, uint256 _round) external; function slashTranscoder(address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee) external; function electActiveTranscoder(uint256 _maxPricePerSegment, bytes32 _blockHash, uint256 _round) external view returns (address); // Public functions function transcoderTotalStake(address _transcoder) public view returns (uint256); function activeTranscoderTotalStake(address _transcoder, uint256 _round) public view returns (uint256); function isRegisteredTranscoder(address _transcoder) public view returns (bool); function getTotalBonded() public view returns (uint256); } /** * @title BondingManager * @dev Manages bonding, transcoder and rewards/fee accounting related operations of the Livepeer protocol */ contract BondingManager is ManagerProxyTarget, IBondingManager { using SafeMath for uint256; using SortedDoublyLL for SortedDoublyLL.Data; using EarningsPool for EarningsPool.Data; // Time between unbonding and possible withdrawl in rounds uint64 public unbondingPeriod; // Number of active transcoders uint256 public numActiveTranscoders; // Max number of rounds that a caller can claim earnings for at once uint256 public maxEarningsClaimsRounds; // Represents a transcoder&#39;s current state struct Transcoder { uint256 lastRewardRound; // Last round that the transcoder called reward uint256 rewardCut; // % of reward paid to transcoder by a delegator uint256 feeShare; // % of fees paid to delegators by transcoder uint256 pricePerSegment; // Price per segment (denominated in LPT units) for a stream uint256 pendingRewardCut; // Pending reward cut for next round if the transcoder is active uint256 pendingFeeShare; // Pending fee share for next round if the transcoder is active uint256 pendingPricePerSegment; // Pending price per segment for next round if the transcoder is active mapping (uint256 => EarningsPool.Data) earningsPoolPerRound; // Mapping of round => earnings pool for the round } // The various states a transcoder can be in enum TranscoderStatus { NotRegistered, Registered } // Represents a delegator&#39;s current state struct Delegator { uint256 bondedAmount; // The amount of bonded tokens uint256 fees; // The amount of fees collected address delegateAddress; // The address delegated to uint256 delegatedAmount; // The amount of tokens delegated to the delegator uint256 startRound; // The round the delegator transitions to bonded phase and is delegated to someone uint256 withdrawRound; // The round at which a delegator can withdraw uint256 lastClaimRound; // The last round during which the delegator claimed its earnings } // The various states a delegator can be in enum DelegatorStatus { Pending, Bonded, Unbonding, Unbonded } // Keep track of the known transcoders and delegators mapping (address => Delegator) private delegators; mapping (address => Transcoder) private transcoders; // Keep track of total bonded tokens uint256 private totalBonded; // Candidate and reserve transcoders SortedDoublyLL.Data private transcoderPool; // Represents the active transcoder set struct ActiveTranscoderSet { address[] transcoders; mapping (address => bool) isActive; uint256 totalStake; } // Keep track of active transcoder set for each round mapping (uint256 => ActiveTranscoderSet) public activeTranscoderSet; // Check if sender is JobsManager modifier onlyJobsManager() { require(msg.sender == controller.getContract(keccak256("JobsManager"))); _; } // Check if sender is RoundsManager modifier onlyRoundsManager() { require(msg.sender == controller.getContract(keccak256("RoundsManager"))); _; } // Check if current round is initialized modifier currentRoundInitialized() { require(roundsManager().currentRoundInitialized()); _; } // Automatically claim earnings from lastClaimRound through the current round modifier autoClaimEarnings() { updateDelegatorWithEarnings(msg.sender, roundsManager().currentRound()); _; } /** * @dev BondingManager constructor. Only invokes constructor of base Manager contract with provided Controller address * @param _controller Address of Controller that this contract will be registered with */ function BondingManager(address _controller) public Manager(_controller) {} /** * @dev Set unbonding period. Only callable by Controller owner * @param _unbondingPeriod Rounds between unbonding and possible withdrawal */ function setUnbondingPeriod(uint64 _unbondingPeriod) external onlyControllerOwner { unbondingPeriod = _unbondingPeriod; ParameterUpdate("unbondingPeriod"); } /** * @dev Set max number of registered transcoders. Only callable by Controller owner * @param _numTranscoders Max number of registered transcoders */ function setNumTranscoders(uint256 _numTranscoders) external onlyControllerOwner { // Max number of transcoders must be greater than or equal to number of active transcoders require(_numTranscoders >= numActiveTranscoders); transcoderPool.setMaxSize(_numTranscoders); ParameterUpdate("numTranscoders"); } /** * @dev Set number of active transcoders. Only callable by Controller owner * @param _numActiveTranscoders Number of active transcoders */ function setNumActiveTranscoders(uint256 _numActiveTranscoders) external onlyControllerOwner { // Number of active transcoders cannot exceed max number of transcoders require(_numActiveTranscoders <= transcoderPool.getMaxSize()); numActiveTranscoders = _numActiveTranscoders; ParameterUpdate("numActiveTranscoders"); } /** * @dev Set max number of rounds a caller can claim earnings for at once. Only callable by Controller owner * @param _maxEarningsClaimsRounds Max number of rounds a caller can claim earnings for at once */ function setMaxEarningsClaimsRounds(uint256 _maxEarningsClaimsRounds) external onlyControllerOwner { maxEarningsClaimsRounds = _maxEarningsClaimsRounds; ParameterUpdate("maxEarningsClaimsRounds"); } /** * @dev The sender is declaring themselves as a candidate for active transcoding. * @param _rewardCut % of reward paid to transcoder by a delegator * @param _feeShare % of fees paid to delegators by a transcoder * @param _pricePerSegment Price per segment (denominated in Wei) for a stream */ function transcoder(uint256 _rewardCut, uint256 _feeShare, uint256 _pricePerSegment) external whenSystemNotPaused currentRoundInitialized { Transcoder storage t = transcoders[msg.sender]; Delegator storage del = delegators[msg.sender]; if (roundsManager().currentRoundLocked()) { // If it is the lock period of the current round // the lowest price previously set by any transcoder // becomes the price floor and the caller can lower its // own price to a point greater than or equal to the price floor // Caller must already be a registered transcoder require(transcoderStatus(msg.sender) == TranscoderStatus.Registered); // Provided rewardCut value must equal the current pendingRewardCut value // This value cannot change during the lock period require(_rewardCut == t.pendingRewardCut); // Provided feeShare value must equal the current pendingFeeShare value // This value cannot change during the lock period require(_feeShare == t.pendingFeeShare); // Iterate through the transcoder pool to find the price floor // Since the caller must be a registered transcoder, the transcoder pool size will always at least be 1 // Thus, we can safely set the initial price floor to be the pendingPricePerSegment of the first // transcoder in the pool address currentTranscoder = transcoderPool.getFirst(); uint256 priceFloor = transcoders[currentTranscoder].pendingPricePerSegment; for (uint256 i = 0; i < transcoderPool.getSize(); i++) { if (transcoders[currentTranscoder].pendingPricePerSegment < priceFloor) { priceFloor = transcoders[currentTranscoder].pendingPricePerSegment; } currentTranscoder = transcoderPool.getNext(currentTranscoder); } // Provided pricePerSegment must be greater than or equal to the price floor and // less than or equal to the previously set pricePerSegment by the caller require(_pricePerSegment >= priceFloor && _pricePerSegment <= t.pendingPricePerSegment); t.pendingPricePerSegment = _pricePerSegment; TranscoderUpdate(msg.sender, t.pendingRewardCut, t.pendingFeeShare, _pricePerSegment, true); } else { // It is not the lock period of the current round // Caller is free to change rewardCut, feeShare, pricePerSegment as it pleases // If caller is not a registered transcoder, it can also register and join the transcoder pool // if it has sufficient delegated stake // If caller is not a registered transcoder and does not have sufficient delegated stake // to join the transcoder pool, it can change rewardCut, feeShare, pricePerSegment // as information signals to delegators in an effort to camapaign and accumulate // more delegated stake // Reward cut must be a valid percentage require(MathUtils.validPerc(_rewardCut)); // Fee share must be a valid percentage require(MathUtils.validPerc(_feeShare)); // Must have a non-zero amount bonded to self require(del.delegateAddress == msg.sender && del.bondedAmount > 0); t.pendingRewardCut = _rewardCut; t.pendingFeeShare = _feeShare; t.pendingPricePerSegment = _pricePerSegment; uint256 delegatedAmount = del.delegatedAmount; // Check if transcoder is not already registered if (transcoderStatus(msg.sender) == TranscoderStatus.NotRegistered) { if (!transcoderPool.isFull()) { // If pool is not full add new transcoder transcoderPool.insert(msg.sender, delegatedAmount, address(0), address(0)); } else { address lastTranscoder = transcoderPool.getLast(); if (delegatedAmount > transcoderPool.getKey(lastTranscoder)) { // If pool is full and caller has more delegated stake than the transcoder in the pool with the least delegated stake: // - Evict transcoder in pool with least delegated stake // - Add caller to pool transcoderPool.remove(lastTranscoder); transcoderPool.insert(msg.sender, delegatedAmount, address(0), address(0)); TranscoderEvicted(lastTranscoder); } } } TranscoderUpdate(msg.sender, _rewardCut, _feeShare, _pricePerSegment, transcoderPool.contains(msg.sender)); } } /** * @dev Delegate stake towards a specific address. * @param _amount The amount of LPT to stake. * @param _to The address of the transcoder to stake towards. */ function bond( uint256 _amount, address _to ) external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { Delegator storage del = delegators[msg.sender]; uint256 currentRound = roundsManager().currentRound(); // Amount to delegate uint256 delegationAmount = _amount; if (delegatorStatus(msg.sender) == DelegatorStatus.Unbonded || delegatorStatus(msg.sender) == DelegatorStatus.Unbonding) { // New delegate // Set start round // Don&#39;t set start round if delegator is in pending state because the start round would not change del.startRound = currentRound.add(1); // If transitioning from unbonding or unbonded state // make sure to zero out withdraw round del.withdrawRound = 0; // Unbonded or unbonding state = no existing delegate // Thus, delegation amount = bonded stake + provided amount // If caller is bonding for the first time or withdrew previously bonded stake, delegation amount = provided amount delegationAmount = delegationAmount.add(del.bondedAmount); } else if (del.delegateAddress != address(0) && _to != del.delegateAddress) { // A registered transcoder cannot delegate its bonded stake toward another address // because it can only be delegated toward itself // In the future, if delegation towards another registered transcoder as an already // registered transcoder becomes useful (i.e. for transitive delegation), this restriction // could be removed require(transcoderStatus(msg.sender) == TranscoderStatus.NotRegistered); // Changing delegate // Set start round del.startRound = currentRound.add(1); // Update amount to delegate with previous delegation amount delegationAmount = delegationAmount.add(del.bondedAmount); // Decrease old delegate&#39;s delegated amount delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(del.bondedAmount); if (transcoderStatus(del.delegateAddress) == TranscoderStatus.Registered) { // Previously delegated to a transcoder // Decrease old transcoder&#39;s total stake transcoderPool.updateKey(del.delegateAddress, transcoderPool.getKey(del.delegateAddress).sub(del.bondedAmount), address(0), address(0)); } } // Delegation amount must be > 0 - cannot delegate to someone without having bonded stake require(delegationAmount > 0); // Update delegate del.delegateAddress = _to; // Update current delegate&#39;s delegated amount with delegation amount delegators[_to].delegatedAmount = delegators[_to].delegatedAmount.add(delegationAmount); if (transcoderStatus(_to) == TranscoderStatus.Registered) { // Delegated to a transcoder // Increase transcoder&#39;s total stake transcoderPool.updateKey(_to, transcoderPool.getKey(del.delegateAddress).add(delegationAmount), address(0), address(0)); } if (_amount > 0) { // Update bonded amount del.bondedAmount = del.bondedAmount.add(_amount); // Update total bonded tokens totalBonded = totalBonded.add(_amount); // Transfer the LPT to the Minter livepeerToken().transferFrom(msg.sender, minter(), _amount); } Bond(_to, msg.sender); } /** * @dev Unbond delegator&#39;s current stake. Delegator enters unbonding state */ function unbond() external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { // Sender must be in bonded state require(delegatorStatus(msg.sender) == DelegatorStatus.Bonded); Delegator storage del = delegators[msg.sender]; uint256 currentRound = roundsManager().currentRound(); // Transition to unbonding phase del.withdrawRound = currentRound.add(unbondingPeriod); // Decrease delegate&#39;s delegated amount delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(del.bondedAmount); // Update total bonded tokens totalBonded = totalBonded.sub(del.bondedAmount); if (transcoderStatus(msg.sender) == TranscoderStatus.Registered) { // If caller is a registered transcoder, resign // In the future, with partial unbonding there would be a check for 0 bonded stake as well resignTranscoder(msg.sender); } if (del.delegateAddress != msg.sender && transcoderStatus(del.delegateAddress) == TranscoderStatus.Registered) { // If delegate is not self and is a registered transcoder, decrease its delegated stake // We do not need to decrease delegated stake if delegate is self because we would have already removed self // from the transcoder pool transcoderPool.updateKey(del.delegateAddress, transcoderPool.getKey(del.delegateAddress).sub(del.bondedAmount), address(0), address(0)); } // Delegator no longer bonded to anyone del.delegateAddress = address(0); // Unbonding delegator does not have a start round del.startRound = 0; Unbond(del.delegateAddress, msg.sender); } /** * @dev Withdraws bonded stake to the caller after unbonding period. */ function withdrawStake() external whenSystemNotPaused currentRoundInitialized { // Delegator must be in the unbonded state require(delegatorStatus(msg.sender) == DelegatorStatus.Unbonded); uint256 amount = delegators[msg.sender].bondedAmount; delegators[msg.sender].bondedAmount = 0; delegators[msg.sender].withdrawRound = 0; // Tell Minter to transfer stake (LPT) to the delegator minter().trustedTransferTokens(msg.sender, amount); WithdrawStake(msg.sender); } /** * @dev Withdraws fees to the caller */ function withdrawFees() external whenSystemNotPaused currentRoundInitialized autoClaimEarnings { // Delegator must have fees require(delegators[msg.sender].fees > 0); uint256 amount = delegators[msg.sender].fees; delegators[msg.sender].fees = 0; // Tell Minter to transfer fees (ETH) to the delegator minter().trustedWithdrawETH(msg.sender, amount); WithdrawFees(msg.sender); } /** * @dev Set active transcoder set for the current round */ function setActiveTranscoders() external whenSystemNotPaused onlyRoundsManager { uint256 currentRound = roundsManager().currentRound(); uint256 activeSetSize = Math.min256(numActiveTranscoders, transcoderPool.getSize()); uint256 totalStake = 0; address currentTranscoder = transcoderPool.getFirst(); for (uint256 i = 0; i < activeSetSize; i++) { activeTranscoderSet[currentRound].transcoders.push(currentTranscoder); activeTranscoderSet[currentRound].isActive[currentTranscoder] = true; uint256 stake = transcoderPool.getKey(currentTranscoder); uint256 rewardCut = transcoders[currentTranscoder].pendingRewardCut; uint256 feeShare = transcoders[currentTranscoder].pendingFeeShare; uint256 pricePerSegment = transcoders[currentTranscoder].pendingPricePerSegment; Transcoder storage t = transcoders[currentTranscoder]; // Set pending rates as current rates t.rewardCut = rewardCut; t.feeShare = feeShare; t.pricePerSegment = pricePerSegment; // Initialize token pool t.earningsPoolPerRound[currentRound].init(stake, rewardCut, feeShare); totalStake = totalStake.add(stake); // Get next transcoder in the pool currentTranscoder = transcoderPool.getNext(currentTranscoder); } // Update total stake of all active transcoders activeTranscoderSet[currentRound].totalStake = totalStake; } /** * @dev Distribute the token rewards to transcoder and delegates. * Active transcoders call this once per cycle when it is their turn. */ function reward() external whenSystemNotPaused currentRoundInitialized { uint256 currentRound = roundsManager().currentRound(); // Sender must be an active transcoder require(activeTranscoderSet[currentRound].isActive[msg.sender]); // Transcoder must not have called reward for this round already require(transcoders[msg.sender].lastRewardRound != currentRound); // Set last round that transcoder called reward transcoders[msg.sender].lastRewardRound = currentRound; // Create reward based on active transcoder&#39;s stake relative to the total active stake // rewardTokens = (current mintable tokens for the round * active transcoder stake) / total active stake uint256 rewardTokens = minter().createReward(activeTranscoderTotalStake(msg.sender, currentRound), activeTranscoderSet[currentRound].totalStake); updateTranscoderWithRewards(msg.sender, rewardTokens, currentRound); Reward(msg.sender, rewardTokens); } /** * @dev Update transcoder&#39;s fee pool * @param _transcoder Transcoder address * @param _fees Fees from verified job claims */ function updateTranscoderWithFees( address _transcoder, uint256 _fees, uint256 _round ) external whenSystemNotPaused onlyJobsManager { // Transcoder must be registered require(transcoderStatus(_transcoder) == TranscoderStatus.Registered); Transcoder storage t = transcoders[_transcoder]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round]; // Add fees to fee pool earningsPool.feePool = earningsPool.feePool.add(_fees); } /** * @dev Slash a transcoder. Slashing can be invoked by the protocol or a finder. * @param _transcoder Transcoder address * @param _finder Finder that proved a transcoder violated a slashing condition. Null address if there is no finder * @param _slashAmount Percentage of transcoder bond to be slashed * @param _finderFee Percentage of penalty awarded to finder. Zero if there is no finder */ function slashTranscoder( address _transcoder, address _finder, uint256 _slashAmount, uint256 _finderFee ) external whenSystemNotPaused onlyJobsManager { Delegator storage del = delegators[_transcoder]; if (del.bondedAmount > 0) { uint256 penalty = MathUtils.percOf(delegators[_transcoder].bondedAmount, _slashAmount); // Decrease bonded stake del.bondedAmount = del.bondedAmount.sub(penalty); // If still bonded // - Decrease delegate&#39;s delegated amount // - Decrease total bonded tokens if (delegatorStatus(_transcoder) == DelegatorStatus.Bonded) { delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(penalty); totalBonded = totalBonded.sub(penalty); } // If registered transcoder, resign it if (transcoderStatus(_transcoder) == TranscoderStatus.Registered) { resignTranscoder(_transcoder); } // Account for penalty uint256 burnAmount = penalty; // Award finder fee if there is a finder address if (_finder != address(0)) { uint256 finderAmount = MathUtils.percOf(penalty, _finderFee); minter().trustedTransferTokens(_finder, finderAmount); // Minter burns the slashed funds - finder reward minter().trustedBurnTokens(burnAmount.sub(finderAmount)); TranscoderSlashed(_transcoder, _finder, penalty, finderAmount); } else { // Minter burns the slashed funds minter().trustedBurnTokens(burnAmount); TranscoderSlashed(_transcoder, address(0), penalty, 0); } } else { TranscoderSlashed(_transcoder, _finder, 0, 0); } } /** * @dev Pseudorandomly elect a currently active transcoder that charges a price per segment less than or equal to the max price per segment for a job * Returns address of elected active transcoder and its price per segment * @param _maxPricePerSegment Max price (in LPT base units) per segment of a stream * @param _blockHash Job creation block hash used as a pseudorandom seed for assigning an active transcoder * @param _round Job creation round */ function electActiveTranscoder(uint256 _maxPricePerSegment, bytes32 _blockHash, uint256 _round) external view returns (address) { uint256 activeSetSize = activeTranscoderSet[_round].transcoders.length; // Create array to store available transcoders charging an acceptable price per segment address[] memory availableTranscoders = new address[](activeSetSize); // Keep track of the actual number of available transcoders uint256 numAvailableTranscoders = 0; // Keep track of total stake of available transcoders uint256 totalAvailableTranscoderStake = 0; for (uint256 i = 0; i < activeSetSize; i++) { address activeTranscoder = activeTranscoderSet[_round].transcoders[i]; // If a transcoder is active and charges an acceptable price per segment add it to the array of available transcoders if (activeTranscoderSet[_round].isActive[activeTranscoder] && transcoders[activeTranscoder].pricePerSegment <= _maxPricePerSegment) { availableTranscoders[numAvailableTranscoders] = activeTranscoder; numAvailableTranscoders++; totalAvailableTranscoderStake = totalAvailableTranscoderStake.add(activeTranscoderTotalStake(activeTranscoder, _round)); } } if (numAvailableTranscoders == 0) { // There is no currently available transcoder that charges a price per segment less than or equal to the max price per segment for a job return address(0); } else { // Pseudorandomly pick an available transcoder weighted by its stake relative to the total stake of all available transcoders uint256 r = uint256(_blockHash) % totalAvailableTranscoderStake; uint256 s = 0; uint256 j = 0; while (s <= r && j < numAvailableTranscoders) { s = s.add(activeTranscoderTotalStake(availableTranscoders[j], _round)); j++; } return availableTranscoders[j - 1]; } } /** * @dev Claim token pools shares for a delegator from its lastClaimRound through the end round * @param _endRound The last round for which to claim token pools shares for a delegator */ function claimEarnings(uint256 _endRound) external whenSystemNotPaused currentRoundInitialized { // End round must be after the last claim round require(delegators[msg.sender].lastClaimRound < _endRound); // End round must not be after the current round require(_endRound <= roundsManager().currentRound()); updateDelegatorWithEarnings(msg.sender, _endRound); } /** * @dev Returns pending bonded stake for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending stake from */ function pendingStake(address _delegator, uint256 _endRound) public view returns (uint256) { uint256 currentRound = roundsManager().currentRound(); Delegator storage del = delegators[_delegator]; // End round must be before or equal to current round and after lastClaimRound require(_endRound <= currentRound && _endRound > del.lastClaimRound); uint256 currentBondedAmount = del.bondedAmount; for (uint256 i = del.lastClaimRound + 1; i <= _endRound; i++) { EarningsPool.Data storage earningsPool = transcoders[del.delegateAddress].earningsPoolPerRound[i]; bool isTranscoder = _delegator == del.delegateAddress; if (earningsPool.hasClaimableShares()) { // Calculate and add reward pool share from this round currentBondedAmount = currentBondedAmount.add(earningsPool.rewardPoolShare(currentBondedAmount, isTranscoder)); } } return currentBondedAmount; } /** * @dev Returns pending fees for a delegator from its lastClaimRound through an end round * @param _delegator Address of delegator * @param _endRound The last round to compute pending fees from */ function pendingFees(address _delegator, uint256 _endRound) public view returns (uint256) { uint256 currentRound = roundsManager().currentRound(); Delegator storage del = delegators[_delegator]; // End round must be before or equal to current round and after lastClaimRound require(_endRound <= currentRound && _endRound > del.lastClaimRound); uint256 currentFees = del.fees; uint256 currentBondedAmount = del.bondedAmount; for (uint256 i = del.lastClaimRound + 1; i <= _endRound; i++) { EarningsPool.Data storage earningsPool = transcoders[del.delegateAddress].earningsPoolPerRound[i]; if (earningsPool.hasClaimableShares()) { bool isTranscoder = _delegator == del.delegateAddress; // Calculate and add fee pool share from this round currentFees = currentFees.add(earningsPool.feePoolShare(currentBondedAmount, isTranscoder)); // Calculate new bonded amount with rewards from this round. Updated bonded amount used // to calculate fee pool share in next round currentBondedAmount = currentBondedAmount.add(earningsPool.rewardPoolShare(currentBondedAmount, isTranscoder)); } } return currentFees; } /** * @dev Returns total bonded stake for an active transcoder * @param _transcoder Address of a transcoder */ function activeTranscoderTotalStake(address _transcoder, uint256 _round) public view returns (uint256) { // Must be active transcoder require(activeTranscoderSet[_round].isActive[_transcoder]); return transcoders[_transcoder].earningsPoolPerRound[_round].totalStake; } /** * @dev Returns total bonded stake for a transcoder * @param _transcoder Address of transcoder */ function transcoderTotalStake(address _transcoder) public view returns (uint256) { return transcoderPool.getKey(_transcoder); } /* * @dev Computes transcoder status * @param _transcoder Address of transcoder */ function transcoderStatus(address _transcoder) public view returns (TranscoderStatus) { if (transcoderPool.contains(_transcoder)) { return TranscoderStatus.Registered; } else { return TranscoderStatus.NotRegistered; } } /** * @dev Computes delegator status * @param _delegator Address of delegator */ function delegatorStatus(address _delegator) public view returns (DelegatorStatus) { Delegator storage del = delegators[_delegator]; if (del.withdrawRound > 0) { // Delegator called unbond if (roundsManager().currentRound() >= del.withdrawRound) { return DelegatorStatus.Unbonded; } else { return DelegatorStatus.Unbonding; } } else if (del.startRound > roundsManager().currentRound()) { // Delegator round start is in the future return DelegatorStatus.Pending; } else if (del.startRound > 0 && del.startRound <= roundsManager().currentRound()) { // Delegator round start is now or in the past return DelegatorStatus.Bonded; } else { // Default to unbonded return DelegatorStatus.Unbonded; } } /** * @dev Return transcoder information * @param _transcoder Address of transcoder */ function getTranscoder( address _transcoder ) public view returns (uint256 lastRewardRound, uint256 rewardCut, uint256 feeShare, uint256 pricePerSegment, uint256 pendingRewardCut, uint256 pendingFeeShare, uint256 pendingPricePerSegment) { Transcoder storage t = transcoders[_transcoder]; lastRewardRound = t.lastRewardRound; rewardCut = t.rewardCut; feeShare = t.feeShare; pricePerSegment = t.pricePerSegment; pendingRewardCut = t.pendingRewardCut; pendingFeeShare = t.pendingFeeShare; pendingPricePerSegment = t.pendingPricePerSegment; } /** * @dev Return transcoder&#39;s token pools for a given round * @param _transcoder Address of transcoder * @param _round Round number */ function getTranscoderEarningsPoolForRound( address _transcoder, uint256 _round ) public view returns (uint256 rewardPool, uint256 feePool, uint256 totalStake, uint256 claimableStake) { EarningsPool.Data storage earningsPool = transcoders[_transcoder].earningsPoolPerRound[_round]; rewardPool = earningsPool.rewardPool; feePool = earningsPool.feePool; totalStake = earningsPool.totalStake; claimableStake = earningsPool.claimableStake; } /** * @dev Return delegator info * @param _delegator Address of delegator */ function getDelegator( address _delegator ) public view returns (uint256 bondedAmount, uint256 fees, address delegateAddress, uint256 delegatedAmount, uint256 startRound, uint256 withdrawRound, uint256 lastClaimRound) { Delegator storage del = delegators[_delegator]; bondedAmount = del.bondedAmount; fees = del.fees; delegateAddress = del.delegateAddress; delegatedAmount = del.delegatedAmount; startRound = del.startRound; withdrawRound = del.withdrawRound; lastClaimRound = del.lastClaimRound; } /** * @dev Returns max size of transcoder pool */ function getTranscoderPoolMaxSize() public view returns (uint256) { return transcoderPool.getMaxSize(); } /** * @dev Returns size of transcoder pool */ function getTranscoderPoolSize() public view returns (uint256) { return transcoderPool.getSize(); } /** * @dev Returns transcoder with most stake in pool */ function getFirstTranscoderInPool() public view returns (address) { return transcoderPool.getFirst(); } /** * @dev Returns next transcoder in pool for a given transcoder * @param _transcoder Address of a transcoder in the pool */ function getNextTranscoderInPool(address _transcoder) public view returns (address) { return transcoderPool.getNext(_transcoder); } /** * @dev Return total bonded tokens */ function getTotalBonded() public view returns (uint256) { return totalBonded; } /** * @dev Return total active stake for a round * @param _round Round number */ function getTotalActiveStake(uint256 _round) public view returns (uint256) { return activeTranscoderSet[_round].totalStake; } /** * @dev Return whether a transcoder was active during a round * @param _transcoder Transcoder address * @param _round Round number */ function isActiveTranscoder(address _transcoder, uint256 _round) public view returns (bool) { return activeTranscoderSet[_round].isActive[_transcoder]; } /** * @dev Return whether a transcoder is registered * @param _transcoder Transcoder address */ function isRegisteredTranscoder(address _transcoder) public view returns (bool) { return transcoderStatus(_transcoder) == TranscoderStatus.Registered; } /** * @dev Remove transcoder */ function resignTranscoder(address _transcoder) internal { uint256 currentRound = roundsManager().currentRound(); if (activeTranscoderSet[currentRound].isActive[_transcoder]) { // Decrease total active stake for the round activeTranscoderSet[currentRound].totalStake = activeTranscoderSet[currentRound].totalStake.sub(activeTranscoderTotalStake(_transcoder, currentRound)); // Set transcoder as inactive activeTranscoderSet[currentRound].isActive[_transcoder] = false; } // Remove transcoder from pools transcoderPool.remove(_transcoder); TranscoderResigned(_transcoder); } /** * @dev Update a transcoder with rewards * @param _transcoder Address of transcoder * @param _rewards Amount of rewards * @param _round Round that transcoder is updated */ function updateTranscoderWithRewards(address _transcoder, uint256 _rewards, uint256 _round) internal { Transcoder storage t = transcoders[_transcoder]; Delegator storage del = delegators[_transcoder]; EarningsPool.Data storage earningsPool = t.earningsPoolPerRound[_round]; // Add rewards to reward pool earningsPool.rewardPool = earningsPool.rewardPool.add(_rewards); // Update transcoder&#39;s delegated amount with rewards del.delegatedAmount = del.delegatedAmount.add(_rewards); // Update transcoder&#39;s total stake with rewards uint256 newStake = transcoderPool.getKey(_transcoder).add(_rewards); transcoderPool.updateKey(_transcoder, newStake, address(0), address(0)); // Update total bonded tokens with claimable rewards totalBonded = totalBonded.add(_rewards); } /** * @dev Update a delegator with token pools shares from its lastClaimRound through a given round * @param _delegator Delegator address * @param _endRound The last round for which to update a delegator&#39;s stake with token pools shares */ function updateDelegatorWithEarnings(address _delegator, uint256 _endRound) internal { Delegator storage del = delegators[_delegator]; // Only will have earnings to claim if you have a delegate // If not delegated, skip the earnings claim process if (del.delegateAddress != address(0)) { // Cannot claim earnings for more than maxEarningsClaimsRounds // This is a number to cause transactions to fail early if // we know they will require too much gas to loop through all the necessary rounds to claim earnings // The user should instead manually invoke `claimEarnings` to split up the claiming process // across multiple transactions require(_endRound.sub(del.lastClaimRound) <= maxEarningsClaimsRounds); uint256 currentBondedAmount = del.bondedAmount; uint256 currentFees = del.fees; for (uint256 i = del.lastClaimRound + 1; i <= _endRound; i++) { EarningsPool.Data storage earningsPool = transcoders[del.delegateAddress].earningsPoolPerRound[i]; if (earningsPool.hasClaimableShares()) { bool isTranscoder = _delegator == del.delegateAddress; var (fees, rewards) = earningsPool.claimShare(currentBondedAmount, isTranscoder); currentFees = currentFees.add(fees); currentBondedAmount = currentBondedAmount.add(rewards); } } // Rewards are bonded by default del.bondedAmount = currentBondedAmount; del.fees = currentFees; } del.lastClaimRound = _endRound; } /** * @dev Return LivepeerToken interface */ function livepeerToken() internal view returns (ILivepeerToken) { return ILivepeerToken(controller.getContract(keccak256("LivepeerToken"))); } /** * @dev Return Minter interface */ function minter() internal view returns (IMinter) { return IMinter(controller.getContract(keccak256("Minter"))); } /** * @dev Return RoundsManager interface */ function roundsManager() internal view returns (IRoundsManager) { return IRoundsManager(controller.getContract(keccak256("RoundsManager"))); } }
Update a delegator with token pools shares from its lastClaimRound through a given round _delegator Delegator address _endRound The last round for which to update a delegator&39;s stake with token pools shares/ Only will have earnings to claim if you have a delegate If not delegated, skip the earnings claim process Cannot claim earnings for more than maxEarningsClaimsRounds This is a number to cause transactions to fail early if we know they will require too much gas to loop through all the necessary rounds to claim earnings The user should instead manually invoke `claimEarnings` to split up the claiming process across multiple transactions
function updateDelegatorWithEarnings(address _delegator, uint256 _endRound) internal { Delegator storage del = delegators[_delegator]; if (del.delegateAddress != address(0)) { require(_endRound.sub(del.lastClaimRound) <= maxEarningsClaimsRounds); uint256 currentBondedAmount = del.bondedAmount; uint256 currentFees = del.fees; for (uint256 i = del.lastClaimRound + 1; i <= _endRound; i++) { EarningsPool.Data storage earningsPool = transcoders[del.delegateAddress].earningsPoolPerRound[i]; if (earningsPool.hasClaimableShares()) { bool isTranscoder = _delegator == del.delegateAddress; var (fees, rewards) = earningsPool.claimShare(currentBondedAmount, isTranscoder); currentFees = currentFees.add(fees); currentBondedAmount = currentBondedAmount.add(rewards); } } del.fees = currentFees; } del.lastClaimRound = _endRound; }
2,107,315
// Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/[email protected] // : MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // : 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 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; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // : MIT 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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File @openzeppelin/contracts/math/[email protected] // : 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; } } // File @openzeppelin/contracts/introspection/[email protected] // : MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // : MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC20/[email protected] // : 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); } // File @openzeppelin/contracts/utils/[email protected] // : 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); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] // : MIT 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] // : MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // : MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File contracts/lib/EIP712MetaTransactionUpgradeable/EIP712BaseUpgradeable.sol //: MIT pragma solidity ^0.7.4; contract EIP712BaseUpgradeable is Initializable { struct EIP712Domain { string name; string version; uint256 salt; address verifyingContract; } bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,uint256 salt,address verifyingContract)" ) ); bytes32 internal domainSeperator; function _initialize(string memory name, string memory version) public virtual initializer { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), getChainID(), address(this) ) ); } function getChainID() internal pure returns (uint256 id) { assembly { id := chainid() } } function getDomainSeperator() private view returns (bytes32) { return domainSeperator; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File contracts/lib/EIP712MetaTransactionUpgradeable/EIP712MetaTransactionUpgradeable.sol //: MIT pragma solidity ^0.7.4; contract EIP712MetaTransactionUpgradeable is Initializable, EIP712BaseUpgradeable { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) private nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function _initialize(string memory _name, string memory _version) public override initializer { EIP712BaseUpgradeable._initialize(_name, _version); } function convertBytesToBytes4(bytes memory inBytes) internal pure returns (bytes4 outBytes4) { if (inBytes.length == 0) { return 0x0; } assembly { outBytes4 := mload(add(inBytes, 32)) } } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable virtual returns (bytes memory) { bytes4 destinationFunctionSig = convertBytesToBytes4(functionSignature); require( destinationFunctionSig != msg.sig, "functionSignature can not be of executeMetaTransaction method" ); MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); nonces[userAddress] = nonces[userAddress].add(1); // Append userAddress at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call(abi.encodePacked(functionSignature, userAddress)); require(success, "Function call not successful"); emit MetaTransactionExecuted(userAddress, msg.sender, functionSignature); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) external view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address user, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { address signer = ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); require(signer != address(0), "Invalid signature"); return signer == user; } function msgSender() internal view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File hardhat/[email protected] // : MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File contracts/NFTMarketplace.sol // : Unlicensed pragma solidity 0.7.4; pragma experimental ABIEncoderV2; // Due to restrictions of the proxy pattern, do not change the following order // of Inheritance contract NFTMarketplace is Initializable, OwnableUpgradeable, EIP712MetaTransactionUpgradeable, ReentrancyGuardUpgradeable { using EnumerableSet for EnumerableSet.UintSet; using SafeMath for uint256; using SafeERC20 for IERC20; event NftListed( uint256 listingId, address nftTokenAddress, uint256 nftTokenId, address listedBy, uint256 paymentType, uint256 paymentAmount, address paymentTokenAddress ); event NftDelisted(uint256 listingId); event NftListingLiked(address indexed likedBy, uint256 nftListingId); event NftListingLikeReverted(address indexed likedBy, uint256 nftListingId); event NftBought(address indexed buyer, uint256 nftListingId); event WithdrawnEthPremiums(address indexed recipient, uint256 amount); event WithdrawnErc20Premiums( address indexed recipient, IERC20 erc20Token, uint256 amount ); // TODO: SWITCH TO ENUMS struct NftListing { uint256 listingId; address nftTokenAddress; uint256 nftTokenId; address payable listedBy; uint256 paymentType; // 0-ETH, 1-ERC20 uint256 paymentAmount; address paymentTokenAddress; } /** * @dev Following are the state variables for this contract * Due to resrictions of the proxy pattern, do not change the type or order * of the state variables. * https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable */ // Listing State uint256 _nextNftListingId; EnumerableSet.UintSet _listedNftTokenIds; mapping(uint256 => NftListing) public nftListingById; // Likes State: user => NftListingId => bool mapping(address => mapping(uint256 => bool)) public hasUserLikedNftListing; // Coinvise premium. If premium rate is 0.2%, is would be stored as 0.2 * 10^decimals = 20 uint256 public premiumPercentage; uint256 public premiumPercentageDecimals; uint256 public nftListingFee; // Whitelisted ERC20 Tokens mapping(address => bool) public isPaymentTokenWhiteListed; bool isPaymentTokenWhiteListActive; // Pausibility bool public isPaused; // Add any new state variables here // End of state variables /** * @dev We cannot have constructors in upgradeable contracts, * therefore we define an initialize function which we call * manually once the contract is deployed. * the initializer modififer ensures that this can only be called once. * in practice, the openzeppelin library automatically calls the intitazie * function once deployed. */ function initialize( uint256 _premiumPercentage, uint256 _premiumPercentageDecimals, uint256 _nftListingFee, address[] memory whiteListedTokens ) public initializer { // Call intialize of Base Contracts OwnableUpgradeable.__Ownable_init(); EIP712MetaTransactionUpgradeable._initialize( "CoinviseNftMarketplace", "1" ); premiumPercentage = _premiumPercentage; premiumPercentageDecimals = _premiumPercentageDecimals; nftListingFee = _nftListingFee; isPaused = false; _nextNftListingId = 1; isPaymentTokenWhiteListActive = true; for (uint256 i = 0; i < whiteListedTokens.length; ++i) { isPaymentTokenWhiteListed[whiteListedTokens[i]] = true; } } // Pausibilty modifier pausable { require(!isPaused, "MARKETPLACE_PAUSED"); _; } modifier onlyOwnerMeta { address _sender = msgSender(); require(_sender == owner(), "UNAUTHORIZED"); _; } function pauseMarketplace() external onlyOwnerMeta { isPaused = true; } function resumeMarketplace() external onlyOwnerMeta { isPaused = false; } // Whitelisting Tokens function setIsWhiteListActive(bool _isPaymentTokenWhiteListActive) external onlyOwnerMeta { isPaymentTokenWhiteListActive = _isPaymentTokenWhiteListActive; } function whiteListTokens(address[] memory tokens) external onlyOwnerMeta { for (uint256 i = 0; i < tokens.length; ++i) { isPaymentTokenWhiteListed[tokens[i]] = true; } } function blackListTokens(address[] memory tokens) external onlyOwnerMeta { for (uint256 i = 0; i < tokens.length; ++i) { isPaymentTokenWhiteListed[tokens[i]] = false; } } function setPremiumPercentage( uint256 _premiumPercentage, uint256 _premiumPercentageDecimals ) external onlyOwnerMeta { premiumPercentage = _premiumPercentage; premiumPercentageDecimals = _premiumPercentageDecimals; } function setNftListingFee(uint256 _nftListingFee) external onlyOwner { nftListingFee = _nftListingFee; } /** * @dev calculates cut given an amount */ function _calculateCut(uint256 amount) internal view returns (uint256) { return amount.mul(premiumPercentage).div( (10**(premiumPercentageDecimals.add(2))) ); } /** * @dev Returns the next id to be used for a new listing */ function _getNextNftListingId() internal returns (uint256) { uint256 listingId = _nextNftListingId; _nextNftListingId = _nextNftListingId.add(1); return listingId; } /** * @dev returns an array of IDs of all the listings currently active on the market */ function getCurrentNftListingIds() external view returns (uint256[] memory) { uint256 length = _listedNftTokenIds.length(); uint256[] memory ids = new uint256[](length); for (uint256 i = 0; i < length; ++i) { ids[i] = _listedNftTokenIds.at(i); } return ids; } function getCurrentNftListingCount() external view returns (uint256) { return _listedNftTokenIds.length(); } /** * @dev Creates a NFT listing. * checks if nft has been approved to transfer by the owner for this contract */ function listNftInEth( address _nftTokenAddress, uint256 _nftTokenId, uint256 _priceInWei ) external payable nonReentrant pausable { address payable _sender = payable(msgSender()); // Check if NFT is approved IERC721 nftContract = IERC721(_nftTokenAddress); require( nftContract.getApproved(_nftTokenId) == address(this), "NFT_NOT_APPROVED" ); require(_priceInWei > 0, "ERR__A_PRICE_MUST_BE_PROVIDED"); require(msg.value == nftListingFee, "ERR__LISTING_FEE_MUST_BE_PAID"); // Create a listing NftListing memory nftListing = NftListing( _getNextNftListingId(), _nftTokenAddress, _nftTokenId, _sender, 0, _priceInWei, address(0) ); _listedNftTokenIds.add(nftListing.listingId); nftListingById[nftListing.listingId] = nftListing; emit NftListed( nftListing.listingId, nftListing.nftTokenAddress, nftListing.nftTokenId, nftListing.listedBy, nftListing.paymentType, nftListing.paymentAmount, nftListing.paymentTokenAddress ); } /** * @dev Creates a NFT listing, payable in an ERC20 Token. * checks if nft has been approved to transfer by the owner for this contract */ function listNftInErc20( address _nftTokenAddress, uint256 _nftTokenId, address _erc20TokenAddress, uint256 _priceInErc20Token ) external nonReentrant pausable { address payable _sender = payable(msgSender()); if (isPaymentTokenWhiteListActive) { require( isPaymentTokenWhiteListed[_erc20TokenAddress], "ERC20_PAYMENT_TOKEN_NOT_WHITELISTED" ); } // Check if NFT is approved IERC721 nftContract = IERC721(_nftTokenAddress); require( nftContract.getApproved(_nftTokenId) == address(this), "NFT_NOT_APPROVED" ); require(_priceInErc20Token > 0, "ERR__A_PRICE_MUST_BE_PROVIDED"); // Create a listing NftListing memory nftListing = NftListing( _getNextNftListingId(), _nftTokenAddress, _nftTokenId, _sender, 1, _priceInErc20Token, _erc20TokenAddress ); _listedNftTokenIds.add(nftListing.listingId); nftListingById[nftListing.listingId] = nftListing; emit NftListed( nftListing.listingId, nftListing.nftTokenAddress, nftListing.nftTokenId, nftListing.listedBy, nftListing.paymentType, nftListing.paymentAmount, nftListing.paymentTokenAddress ); } /** * @dev Function for delisting a NFT from marketplace. Can be called if creator wants * to manually removbe the listing, or once the NFT has been bought */ function _unlistNft(uint256 _nftListingId) internal { _listedNftTokenIds.remove(_nftListingId); delete nftListingById[_nftListingId]; emit NftDelisted(_nftListingId); } /** * @dev Called by listing creator, to delist a NFT before it's bought by someone */ function unlistNftByListingCreator(uint256 _nftListingId) external pausable { address _sender = msgSender(); require( _sender == nftListingById[_nftListingId].listedBy, "UNAUTHORIZED" ); require(_listedNftTokenIds.contains(_nftListingId), "ALREADY_DELISTED"); _unlistNft(_nftListingId); } /** * @dev Transfers an NFT from lister to buyer if conditions are met */ function buyNftInEth(uint256 _nftListingId) external payable pausable { address _sender = msgSender(); NftListing memory nftListing = nftListingById[_nftListingId]; // Lister cannot be buyer require(nftListing.listedBy != _sender, "BUYER_CANNOT_BE_LISTER"); // Validate the listing require(_listedNftTokenIds.contains(_nftListingId), "ALREADY_DELISTED"); require(nftListing.paymentType == 0, "WRONG_PAYMENT_TYPE"); // Validate amount sent uint256 listingAmountWei = nftListing.paymentAmount; uint256 expectedAmountWei = listingAmountWei.add( _calculateCut(listingAmountWei) ); require(msg.value == expectedAmountWei, "INVALID_FUNDS_SENT"); // Check if NFT is approved IERC721 nftContract = IERC721(nftListing.nftTokenAddress); require( nftContract.getApproved(nftListing.nftTokenId) == address(this), "NFT_NOT_APPROVED" ); // Transfer ETH to lister nftListing.listedBy.transfer(listingAmountWei); // Transfer NFT from lister to buyer nftContract.safeTransferFrom( nftListing.listedBy, _sender, nftListing.nftTokenId ); // Close the listing _unlistNft(_nftListingId); // Emit emit NftBought(_sender, _nftListingId); } /** * @dev Transfers an NFT Token on payment by ERC20 */ function buyNftInErc20Tokens(uint256 _nftListingId) external pausable { address _sender = msgSender(); NftListing memory nftListing = nftListingById[_nftListingId]; // Lister cannot be buyer require(nftListing.listedBy != _sender, "BUYER_CANNOT_BE_LISTER"); // Validate the listing require(_listedNftTokenIds.contains(_nftListingId), "ALREADY_DELISTED"); require(nftListing.paymentType == 1, "WRONG_PAYMENT_TYPE"); // Validate token approved amount uint256 listingAmountInTokens = nftListing.paymentAmount; uint256 expectedAmountInTokens = listingAmountInTokens.add( _calculateCut(listingAmountInTokens) ); IERC20 erc20Token = IERC20(nftListing.paymentTokenAddress); require( erc20Token.allowance(_sender, address(this)) >= expectedAmountInTokens, "INSUFFICIENT_TOKEN_ALLOWANCE" ); // Check if NFT is approved IERC721 nftContract = IERC721(nftListing.nftTokenAddress); require( nftContract.getApproved(nftListing.nftTokenId) == address(this), "NFT_NOT_APPROVED" ); // Transfer funds to marketContract; erc20Token.safeTransferFrom( _sender, address(this), expectedAmountInTokens ); // Transfer asked price to lister erc20Token.safeTransfer(nftListing.listedBy, listingAmountInTokens); // Transfer NFT from lister to buyer nftContract.safeTransferFrom( nftListing.listedBy, _sender, nftListing.nftTokenId ); // Close the listing _unlistNft(_nftListingId); // Emit emit NftBought(_sender, _nftListingId); } /** * @dev Increments the like counter for a listing if's it's actvie */ function likeNftListing(uint256 _nftListingId) external pausable { address _sender = msgSender(); require(_listedNftTokenIds.contains(_nftListingId), "ALREADY_DELISTED"); require( !hasUserLikedNftListing[_sender][_nftListingId], "ALREADY_LIKED" ); hasUserLikedNftListing[_sender][_nftListingId] = true; emit NftListingLiked(_sender, _nftListingId); } /** * @dev Decrements the like counter for a listing if's it's actvie */ function undoLikeNftListing(uint256 _nftListingId) external pausable { address _sender = msgSender(); require(_listedNftTokenIds.contains(_nftListingId), "ALREADY_DELISTED"); require(hasUserLikedNftListing[_sender][_nftListingId], "NOT_LIKED"); hasUserLikedNftListing[_sender][_nftListingId] = false; emit NftListingLikeReverted(_sender, _nftListingId); } /** * @dev Sends all eth to a specified address */ function withdrawEthPremiums(address payable _to) external onlyOwnerMeta { _to.transfer(address(this).balance); emit WithdrawnEthPremiums(_to, address(this).balance); } /** * @dev Sends all balance of specific ERC20 token to address */ function withdrawErc20Premiums(address _to, IERC20 erc20Token) external onlyOwnerMeta { uint256 balance = erc20Token.balanceOf(address(this)); erc20Token.safeTransfer(_to, balance); emit WithdrawnErc20Premiums(_to, erc20Token, balance); } fallback() external payable {} receive() external payable {} }
Whitelisting Tokens
function setIsWhiteListActive(bool _isPaymentTokenWhiteListActive) external onlyOwnerMeta { isPaymentTokenWhiteListActive = _isPaymentTokenWhiteListActive; }
1,353,400
./partial_match/1/0x7D01adB5336704A44C28aa6274c6687ec9FBC6D2/sources/SakeSwapMigrator.sol
Removes liquidity Adds liquidity to SakeSwap Refund sender any remaining tokens
function _migrate(IRouter router, ISakeSwapERC20 pair, address token0, address token1, uint256 value) internal { pair.transferFrom(msg.sender, address(this), value); pair.approve(address(router), value); router.removeLiquidity( token0, token1, value, 0, 0, address(this), now + 60 ); uint256 bal0 = ISakeSwapERC20(token0).balanceOf(address(this)); uint256 bal1 = ISakeSwapERC20(token1).balanceOf(address(this)); ISakeSwapERC20(token0).approve(address(sakeRouter), bal0); ISakeSwapERC20(token1).approve(address(sakeRouter), bal1); sakeRouter.addLiquidity( token0, token1, bal0, bal1, 0, 0, msg.sender, now + 60 ); uint256 remainBal0 = ISakeSwapERC20(token0).balanceOf(address(this)); uint256 remainBal1 = ISakeSwapERC20(token1).balanceOf(address(this)); if (remainBal0 > 0) ISakeSwapERC20(token0).transfer(msg.sender, remainBal0); if (remainBal1 > 0) ISakeSwapERC20(token1).transfer(msg.sender, remainBal1); }
4,096,247
./partial_match/1/0x9908e89CfCF86eF44b6e3b2F65A6d871714ACe39/sources/Queue.sol
Used to pay to current investors Each new transaction processes 1 - 4+ investors in the head of queue depending on balance and gas left We will do cycle on the queue
function pay() internal { uint money = address(this).balance; uint multiplier = 120; for (uint i = 0; i < queue.length; i++){ uint totalPayout = dep.deposit * multiplier / 100; uint leftPayout; if (totalPayout > dep.payout) { leftPayout = totalPayout - dep.payout; } if (leftPayout > 0) { money -= leftPayout; } delete queue[idx]; } }
4,423,677
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import './Mars26.sol'; import './MarsStorage.sol'; /** * @title Mars contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Mars is Ownable, ERC721Enumerable { using SafeMath for uint256; bytes32 private _provenanceHash; uint256 internal _maxSupply; uint256 private _nameChangePrice; uint256 private _saleStartTimestamp; uint256 private _revealTimestamp; uint256[6] private _priceIntervalSupplyLimits; uint256 private _startingIndexBlock; uint256 internal _startingIndex; mapping (uint256 => string) private _tokenNames; mapping (string => bool) private _reservedNames; mapping (uint256 => bool) private _mintedBeforeReveal; Mars26 private _m26; MarsStorage private _storage; event NameChange (uint256 indexed maskIndex, string newName); /** * @dev Sets immutable values of contract. */ constructor ( bytes32 provenanceHash_, address m26Address_, uint256 nameChangePrice_, uint256 saleStartTimestamp_, uint256 revealTimestamp_, uint256 maxSupply_, uint256[6] memory priceIntervalSupplyLimits_ ) ERC721("Mars", "MARS") { _provenanceHash = provenanceHash_; _m26 = Mars26(m26Address_); _nameChangePrice = nameChangePrice_; _saleStartTimestamp = saleStartTimestamp_; _revealTimestamp = revealTimestamp_; for (uint i = 1; i < priceIntervalSupplyLimits_.length; i++) { require( priceIntervalSupplyLimits_[i - 1] < priceIntervalSupplyLimits_[i], "Price intervale supply limit need to ascending" ); } _priceIntervalSupplyLimits = priceIntervalSupplyLimits_; _maxSupply = maxSupply_; _storage = new MarsStorage(maxSupply_); } /** * @dev Returns provenance hash digest set during initialization of contract. * * The provenance hash is derived by concatenating all existing IPFS CIDs (v0) * of the Mars NFTs and hashing the concatenated string using SHA2-256. * Note that the CIDs were concatenated and hashed in their base58 representation. */ function provenanceHash() public view returns (bytes32) { return _provenanceHash; } /** * @dev Returns address of Mars26 ERC-20 token contract. */ function m26Address() public view returns (address) { return address(_m26); } /** * @dev Returns address of connected storage contract. */ function storageAddress() public view returns (address) { return address(_storage); } /** * @dev Returns max number of NFTs that can be minted. */ function maxSupply() public view returns (uint256) { return _maxSupply; } /** * @dev Returns the MNCT price for changing the name of a token. */ function nameChangePrice() public view returns (uint256) { return _nameChangePrice; } /** * @dev Returns the start timestamp of the initial sale. */ function saleStartTimestamp() public view returns (uint256) { return _saleStartTimestamp; } /** * @dev Returns the reveal timestamp after which the token ids will be assigned. */ function revealTimestamp() public view returns (uint256) { return _revealTimestamp; } /** * @dev Returns the set upper supply limits which determine the NFT price during sale. */ function priceIntervalSupplyLimits() public view returns (uint256[6] memory) { return _priceIntervalSupplyLimits; } /** * @dev Returns the randomized starting index to assign and reveal token ids to * intial sequence of NFTs. */ function startingIndex() public view returns (uint256) { return _startingIndex; } /** * @dev Returns the randomized starting index block which is used to derive * {_startingIndex} from. */ function startingIndexBlock() public view returns (uint256) { return _startingIndexBlock; } /** * @dev See {MarsStorage.initialSequenceTokenCID} */ function initialSequenceTokenCID(uint256 initialSequenceIndex) public view returns (string memory) { return _storage.initialSequenceTokenCID(initialSequenceIndex); } /** * @dev Returns if {nameString} has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _reservedNames[_toLower(nameString)]; } /** * @dev Returns reverved name for given token id. */ function tokenNames(uint256 tokenId) public view returns (string memory) { return _tokenNames[tokenId]; } /** * @dev Returns the set token URI, i.e. IPFS v0 CID, of {tokenId}. * Prefixed with ipfs:// */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); require(_startingIndex > 0, "Tokens have not been assigned yet"); uint256 initialSequenceIndex = _toInitialSequenceIndex(tokenId); return tokenURIOfInitialSequenceIndex(initialSequenceIndex); } /** * @dev Returns the set token URI, i.e. IPFS v0 CID, of {initialSequenceIndex}. * Prefixed with ipfs:// */ function tokenURIOfInitialSequenceIndex(uint256 initialSequenceIndex) public view returns (string memory) { require(_startingIndex > 0, "Tokens have not been assigned yet"); string memory tokenCID = initialSequenceTokenCID(initialSequenceIndex); string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return tokenCID; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(tokenCID).length > 0) { return string(abi.encodePacked(base, tokenCID)); } return base; } /** * @dev Returns if the NFT has been minted before reveal phase. */ function isMintedBeforeReveal(uint256 index) public view returns (bool) { return _mintedBeforeReveal[index]; } /** * @dev Gets current NFT price based on already minted tokens. */ function getNFTPrice() public view returns (uint256) { uint currentSupply = totalSupply(); if (currentSupply < _priceIntervalSupplyLimits[0]) { return 0.05 ether; } else if (currentSupply < _priceIntervalSupplyLimits[1]) { return 0.1 ether; } else if (currentSupply < _priceIntervalSupplyLimits[2]) { return 0.2 ether; } else if (currentSupply < _priceIntervalSupplyLimits[3]) { return 0.4 ether; } else if (currentSupply < _priceIntervalSupplyLimits[4]) { return 1 ether; } else if (currentSupply < _priceIntervalSupplyLimits[5]) { return 3 ether; } else { return 26 ether; } } /** * @dev Mints Mars NFTs */ function mintNFT(uint256 numberOfNfts) public payable { require(block.timestamp >= _saleStartTimestamp, "Sale has not started"); require(totalSupply() < _maxSupply, "Sale has already ended"); require(numberOfNfts > 0, "Cannot buy 0 NFTs"); require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once"); require(totalSupply().add(numberOfNfts) <= _maxSupply, "Exceeds max number of NFTs in existence"); require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct"); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); require(mintIndex < _maxSupply, "Exceeds max number of NFTs in existence"); if (block.timestamp < _revealTimestamp) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } // Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense if (_startingIndexBlock == 0 && (totalSupply() == _maxSupply || block.timestamp >= _revealTimestamp)) { _startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(_startingIndex == 0, "Starting index is already set"); require(_startingIndexBlock != 0, "Starting index block must be set"); _startingIndex = uint(blockhash(_startingIndexBlock)) % _maxSupply; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(_startingIndexBlock) > 255) { _startingIndex = uint(blockhash(block.number - 1)) % _maxSupply; } // Prevent default sequence if (_startingIndex == 0) { _startingIndex = _startingIndex.add(1); } } /** * @dev Changes the name for Mars tile tokenId */ function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(_validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenNames[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); _m26.transferFrom(msg.sender, address(this), _nameChangePrice); // If already named, dereserve old name if (bytes(_tokenNames[tokenId]).length > 0) { _toggleReserveName(_tokenNames[tokenId], false); } _toggleReserveName(newName, true); _tokenNames[tokenId] = newName; _m26.burn(_nameChangePrice); emit NameChange(tokenId, newName); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner public { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev See {MarsStorage.setInitialSequenceTokenHashes} */ function setInitialSequenceTokenHashes(bytes32[] memory tokenHashes) onlyOwner public { _storage.setInitialSequenceTokenHashes(tokenHashes); } /** * @dev See {MarsStorage.setInitialSequenceTokenHashesAtIndex} */ function setInitialSequenceTokenHashesAtIndex( uint256 startIndex, bytes32[] memory tokenHashes ) public onlyOwner { _storage.setInitialSequenceTokenHashesAtIndex(startIndex, tokenHashes); } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function _validateName(string memory str) private pure returns (bool){ bytes memory b = bytes(str); if (b.length < 1) return false; if (b.length > 50) return false; // Cannot be longer than 25 characters if (b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for (uint i; i < b.length; i++) { bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function _toLower(string memory str) private pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function _toggleReserveName(string memory str, bool isReserve) internal { _reservedNames[_toLower(str)] = isReserve; } function _baseURI() internal pure override returns (string memory) { return "ipfs://"; } function _toInitialSequenceIndex(uint256 tokenId) internal view returns (uint256) { return (tokenId + _startingIndex) % _maxSupply; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Mars.sol"; /** * Mars26 Contract * @dev Extends standard ERC20 contract */ contract Mars26 is ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public constant INITIAL_ALLOTMENT = 2026 * (10 ** 18); uint256 public constant PRE_REVEAL_MULTIPLIER = 2; uint256 private constant _SECONDS_IN_A_DAY = 86400; uint256 private _emissionStartTimestamp; uint256 private _emissionEndTimestamp; uint256 private _emissionPerDay; mapping(uint256 => uint256) private _lastClaim; Mars private _mars; /** * @dev Sets immutable values of contract. */ constructor ( uint256 emissionStartTimestamp_, uint256 emissionEndTimestamp_, uint256 emissionPerDay_ ) ERC20("Mars26", "M26") { _emissionStartTimestamp = emissionStartTimestamp_; _emissionEndTimestamp = emissionEndTimestamp_; _emissionPerDay = emissionPerDay_; } function emissionStartTimestamp() public view returns (uint256) { return _emissionStartTimestamp; } function emissionEndTimestamp() public view returns (uint256) { return _emissionEndTimestamp; } function emissionPerDay() public view returns (uint256) { return _emissionPerDay; } function marsAddress() public view returns (address) { return address(_mars); } /** * @dev Sets Mars contract address. Can only be called once by owner. */ function setMarsAddress(address marsAddress_) public onlyOwner { require(address(_mars) == address(0), "Already set"); _mars = Mars(marsAddress_); } /** * @dev Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}. */ function lastClaim(uint256 tokenIndex) public view returns (uint256) { require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp; return lastClaimed; } /** * @dev Returns amount of accumulated M26s for {tokenIndex}. */ function accumulated(uint256 tokenIndex) public view returns (uint256) { require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet"); require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = lastClaim(tokenIndex); // Sanity check if last claim was on or after emission end if (lastClaimed >= _emissionEndTimestamp) return 0; uint256 accumulationPeriod = block.timestamp < _emissionEndTimestamp ? block.timestamp : _emissionEndTimestamp; // Getting the min value of both uint256 totalAccumulated = accumulationPeriod .sub(lastClaimed) .mul(_emissionPerDay) .div(_SECONDS_IN_A_DAY); // If claim hasn't been done before for the index, add initial allotment (plus prereveal multiplier if applicable) if (lastClaimed == _emissionStartTimestamp) { uint256 initialAllotment = _mars.isMintedBeforeReveal(tokenIndex) == true ? INITIAL_ALLOTMENT.mul(PRE_REVEAL_MULTIPLIER) : INITIAL_ALLOTMENT; totalAccumulated = totalAccumulated.add(initialAllotment); } return totalAccumulated; } /** * @dev Claim mints M26s and supports multiple token indices at once. */ function claim(uint256[] memory tokenIndices) public returns (uint256) { require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet"); uint256 totalClaimQty = 0; for (uint i = 0; i < tokenIndices.length; i++) { // Sanity check for non-minted index require(tokenIndices[i] < _mars.totalSupply(), "NFT at index has not been minted yet"); // Duplicate token index check for (uint j = i + 1; j < tokenIndices.length; j++) { require(tokenIndices[i] != tokenIndices[j], "Duplicate token index"); } uint tokenIndex = tokenIndices[i]; require(_mars.ownerOf(tokenIndex) == msg.sender, "Sender is not the owner"); uint256 claimQty = accumulated(tokenIndex); if (claimQty != 0) { totalClaimQty = totalClaimQty.add(claimQty); _lastClaim[tokenIndex] = block.timestamp; } } require(totalClaimQty != 0, "No accumulated M26"); _mint(msg.sender, totalClaimQty); increaseAllowance(address(_mars), totalClaimQty); return totalClaimQty; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title MarsStorage contract */ contract MarsStorage is Ownable { using SafeMath for uint256; // hash code: 0x12 (SHA-2) and digest length: 0x20 (32 bytes / 256 bits) bytes2 public constant MULTIHASH_PREFIX = 0x1220; // IPFS CID Version: v0 uint256 public constant CID_VERSION = 0; // IPFS v0 CIDs in hexadecimal without multihash prefix ordered by initial sequence bytes32[] private _intitialSequenceTokenHashes; uint256 internal _maxSupply; bytes internal constant _ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; /** * @dev Sets immutable values of contract. */ constructor (uint256 maxSupply_) { _maxSupply = maxSupply_; } /** * @dev Returns the IPFS v0 CID of {initialSequenceIndex}. * * The returned values can be concatenated and hashed using SHA2-256 to verify the * provenance hash. */ function initialSequenceTokenCID(uint256 initialSequenceIndex) public view returns (string memory) { bytes memory tokenCIDHex = abi.encodePacked( MULTIHASH_PREFIX, _intitialSequenceTokenHashes[initialSequenceIndex] ); string memory tokenCID = _toBase58(tokenCIDHex); return tokenCID; } /** * @dev Sets token hashes in the initially set order as verifiable through * {_provenanceHash}. * * Provided {tokenHashes} are IPFS v0 CIDs in hexadecimal without the prefix 0x1220 * and ordered in the initial sequence. */ function setInitialSequenceTokenHashes(bytes32[] memory tokenHashes) onlyOwner public { setInitialSequenceTokenHashesAtIndex(_intitialSequenceTokenHashes.length, tokenHashes); } /** * @dev Sets token hashes in the initially set order starting at {startIndex}. */ function setInitialSequenceTokenHashesAtIndex( uint256 startIndex, bytes32[] memory tokenHashes ) public onlyOwner { require(startIndex <= _intitialSequenceTokenHashes.length); for (uint256 i = 0; i < tokenHashes.length; i++) { if ((i + startIndex) >= _intitialSequenceTokenHashes.length) { _intitialSequenceTokenHashes.push(tokenHashes[i]); } else { _intitialSequenceTokenHashes[i + startIndex] = tokenHashes[i]; } } require(_intitialSequenceTokenHashes.length <= _maxSupply); } // Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol) // @author Martin Lundfall ([email protected]) // @dev Converts hex string to base 58 function _toBase58(bytes memory source) internal pure returns (string memory) { if (source.length == 0) return new string(0); uint8[] memory digits = new uint8[](46); digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i < source.length; ++i) { uint256 carry = uint8(source[i]); for (uint256 j = 0; j < digitlength; ++j) { carry += uint256(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } return string(_toAlphabet(_reverse(_truncate(digits, digitlength)))); } function _truncate(uint8[] memory array, uint8 length) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](length); for (uint256 i = 0; i < length; i++) { output[i] = array[i]; } return output; } function _reverse(uint8[] memory input) internal pure returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint256 i = 0; i < input.length; i++) { output[i] = input[input.length - 1 - i]; } return output; } function _toAlphabet(uint8[] memory indices) internal pure returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint256 i = 0; i < indices.length; i++) { output[i] = _ALPHABET[indices[i]]; } return output; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.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 || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "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; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All 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_; } /** * @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 this function is * overloaded; * * 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 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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); }
Returns provenance hash digest set during initialization of contract. The provenance hash is derived by concatenating all existing IPFS CIDs (v0) of the Mars NFTs and hashing the concatenated string using SHA2-256. Note that the CIDs were concatenated and hashed in their base58 representation./
function provenanceHash() public view returns (bytes32) { return _provenanceHash; }
7,025,223
/** *Submitted for verification at Etherscan.io on 2021-04-26 */ // Sources flattened with hardhat v2.1.2 https://hardhat.org // File contracts/interfaces/IERC20.sol // SPDX-License-Identifier: MIT; pragma solidity ^0.7.6; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libraries/SafeMath.sol pragma solidity ^0.7.6; /** * @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 contracts/access/Context.sol pragma solidity ^0.7.6; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/security/Pausable.sol pragma solidity ^0.7.6; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File contracts/access/Ownable.sol pragma solidity ^0.7.6; abstract contract Ownable is Pausable { address public _owner; address public _admin; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address ownerAddress) { _owner = _msgSender(); _admin = ownerAddress; emit OwnershipTransferred(address(0), _owner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(_admin == _msgSender(), "Ownable: caller is not the admin"); _; } /** * @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 onlyAdmin { emit OwnershipTransferred(_owner, _admin); _owner = _admin; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/UnifarmToken.sol pragma solidity ^0.7.6; contract UnifarmToken is Ownable { /// @notice EIP-20 token name for this token string public constant name = "UNIFARM Token"; /// @notice EIP-20 token symbol for this token string public constant symbol = "UFARM"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public totalSupply = 1000000000e18; // 1 billion UFARM using SafeMath for uint256; mapping(address => mapping(address => uint256)) internal allowances; mapping(address => uint256) internal balances; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; mapping(address => uint256) public lockedTokens; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice The 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 Construct a new UFARM token * @param account The initial account to grant all the tokens */ constructor(address account) Ownable(account) { balances[account] = uint256(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @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) { require(spender != address(0), "UFARM::approve: invalid spender address"); uint256 amount; if (rawAmount == uint256(-1)) { amount = uint256(-1); } else { amount = rawAmount; //safe96(rawAmount, "UFARM::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, 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) external returns (bool) { require(spender != address(0), "UFARM::approve: invalid spender address"); uint256 newAllowance = allowances[_msgSender()][spender].add(addedValue); allowances[_msgSender()][spender] = newAllowance; emit Approval(msg.sender, spender, newAllowance); 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) external returns (bool) { require(spender != address(0), "UFARM::approve: invalid spender address"); uint256 currentAllowance = allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); allowances[_msgSender()][spender] = currentAllowance.sub(subtractedValue); emit Approval(msg.sender, spender, currentAllowance.sub(subtractedValue)); 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 rawAmount 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, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { uint256 amount; if (rawAmount == uint256(-1)) { amount = uint256(-1); } else { amount = rawAmount; //safe96(rawAmount, "UFARM::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "UFARM::permit: invalid signature"); require(signatory == owner, "UFARM::permit: unauthorized"); require(block.timestamp <= deadline, "UFARM::permit: signature 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 (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) { _transferTokens(msg.sender, dst, rawAmount); 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) { address spender = msg.sender; uint256 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(rawAmount, "UFARM::transferFrom: exceeds allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, rawAmount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external returns (bool) { _delegate(msg.sender, delegatee); return true; } /** * @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 ) external { require(block.timestamp <= expiry, "UFARM::delegateBySig: signature expired"); bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "UFARM::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "UFARM::delegateBySig: invalid nonce"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { 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) external view returns (uint256) { require(blockNumber < block.number, "UFARM::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; } /** * @notice burn the token of any token holder. * @dev balance should be greater than amount. function will revert will balance is less than amount. * @param holder the addrress of token holder. * @param amount number of tokens to burn. * @return true when burnToken succeeded. */ function burnToken(address holder, uint256 amount) external onlyOwner returns (bool) { require(balances[holder] >= amount, "UFARM::burnToken: Insufficient balance"); balances[holder] = balances[holder].sub(amount); totalSupply = totalSupply.sub(amount); _moveDelegates(delegates[holder], delegates[address(0)], amount); return true; } /** * @notice lock the token of any token holder. * @dev balance should be greater than amount. function will revert will balance is less than amount. * @param holder the addrress of token holder. * @param amount number of tokens to burn. * @return true when lockToken succeeded. */ function lockToken(address holder, uint256 amount) external onlyOwner returns (bool) { require(balances[holder] >= amount, "UFARM::burnToken: Insufficient balance"); balances[holder] = balances[holder].sub(amount); lockedTokens[holder] = lockedTokens[holder].add(amount); _moveDelegates(delegates[holder], delegates[address(0)], amount); return true; } /** * @notice unLock the token of any token holder. * @dev locked balance should be greater than amount. function will revert will locked balance is less than amount. * @param holder the addrress of token holder. * @param amount number of tokens to burn. * @return true when unLockToken succeeded. */ function unlockToken(address holder, uint256 amount) external onlyOwner returns (bool) { require(lockedTokens[holder] >= amount, "UFARM::unlockToken: OverflowLocked balance"); lockedTokens[holder] = lockedTokens[holder].sub(amount); balances[holder] = balances[holder].add(amount); _moveDelegates(delegates[address(0)], delegates[holder], amount); return true; } /** * @notice set the delegatee. * @dev delegatee address should not be zero address. * @param delegator the addrress of token holder. * @param delegatee number of tokens to burn. */ function _delegate(address delegator, address delegatee) internal { require(delegatee != address(0), "UFARM::_delegate: invalid delegatee address"); address currentDelegate = delegates[delegator]; uint256 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } /** * @notice transfer tokens to src --> dst. * @dev src address should be valid ethereum address. * @dev dst address should be valid ethereum address. * @dev amount should be greater than zero. * @param src the source address. * @param dst the destination address. * @param amount number of token to transfer. */ function _transferTokens( address src, address dst, uint256 amount ) internal { require(src != address(0), "UFARM::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "UFARM::_transferTokens: cannot transfer to the zero address"); require(amount > 0, "UFARM::_transferTokens: invalid amount wut??"); balances[src] = balances[src].sub(amount, "UFARM::_transferTokens: exceeds balance"); balances[dst] = balances[dst].add(amount); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } /** * @notice transfer the vote token. * @dev srcRep address should be valid ethereum address. * @dev dstRep address should be valid ethereum address. * @dev amount should be greater than zero. * @param srcRep the source vote address. * @param dstRep the destination vote address. * @param amount number of vote token to transfer. */ function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * @notice write checkpoint for delegatee. * @dev blocknumber should be uint32. * @param delegatee the address of delegatee. * @param nCheckpoints no of checkpoints. * @param oldVotes number of old votes. * @param newVotes number of new votes. */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "UFARM::_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); } /** * @notice safe32 function using for uint32 type. * @param n the data. * @param errorMessage set the errorMessage. * @return uint32 data. */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * @notice get the chainId from inline assembly. * @return uint256 chainId of Node. */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account 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) { address spender = msg.sender; uint256 spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(rawAmount, "UFARM::transferFrom: exceeds allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, rawAmount); return true; }
10,680,945
./full_match/4/0xCfe89F7e97bAf8C6782DffD6cc58F371afd9d3c7/sources/contracts/GeneScience.sol
return the expressing traits _genes the long number expressing cat genes
function expressingTraits(uint256 _genes) public pure returns(uint8[12] memory) { uint8[12] memory express; for(uint256 i = 0; i < 12; i++) { express[i] = _get5Bits(_genes, i * 4); } return express; }
12,363,215
./full_match/1/0x38D8FA043913e8Ef6466d01BEF4Af42Cafa3b235/sources/contracts/manager/DelegatedManager.sol
Add new operator(s) address(es) _operators New operator to add/
function _addOperators(address[] memory _operators) internal { for (uint256 i = 0; i < _operators.length; i++) { address operator = _operators[i]; require(!operatorAllowlist[operator], "Operator already added"); operators.push(operator); operatorAllowlist[operator] = true; emit OperatorAdded(operator); } }
3,150,764
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul // WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that // requires ABIEncoderV2. Exercise caution when calling that specific function. pragma experimental ABIEncoderV2; interface DharmaSmartWalletImplementationV1Interface { event CallSuccess( bytes32 actionID, bool rolledBack, uint256 nonce, address to, uint256 value, bytes data, bytes returnData ); event CallFailure( bytes32 actionID, uint256 nonce, address to, uint256 value, bytes data, string revertReason ); // ABIEncoderV2 uses an array of Calls for executing generic batch calls. struct Call { address to; uint96 value; bytes data; } // ABIEncoderV2 uses an array of CallReturns for handling generic batch calls. struct CallReturn { bool ok; bytes returnData; } function withdrawEther( uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function executeAction( address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function recover(address newUserSigningKey) external; function executeActionWithAtomicBatchCalls( Call[] calldata calls, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool[] memory ok, bytes[] memory returnData); function getNextGenericActionID( address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getGenericActionID( address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getNextGenericAtomicBatchActionID( Call[] calldata calls, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getGenericAtomicBatchActionID( Call[] calldata calls, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV3Interface { event Cancel(uint256 cancelledNonce); event EthWithdrawal(uint256 amount, address recipient); } interface DharmaSmartWalletImplementationV4Interface { event Escaped(); function setEscapeHatch( address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function removeEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function permanentlyDisableEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function escape(address token) external; } interface DharmaSmartWalletImplementationV7Interface { // Fires when a new user signing key is set on the smart wallet. event NewUserSigningKey(address userSigningKey); // Fires when an error occurs as part of an attempted action. event ExternalError(address indexed source, string revertReason); // The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets. enum AssetType { DAI, USDC, ETH, SAI } // Actions, or protected methods (i.e. not deposits) each have an action type. enum ActionType { Cancel, SetUserSigningKey, Generic, GenericAtomicBatch, SAIWithdrawal, USDCWithdrawal, ETHWithdrawal, SetEscapeHatch, RemoveEscapeHatch, DisableEscapeHatch, DAIWithdrawal, SignatureVerification, TradeEthForDai, DAIBorrow, USDCBorrow } function initialize(address userSigningKey) external; function repayAndDeposit() external; function withdrawDai( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function withdrawUSDC( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok); function cancel( uint256 minimumActionGas, bytes calldata signature ) external; function setUserSigningKey( address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external; function migrateSaiToDai() external; function migrateCSaiToDDai() external; function migrateCDaiToDDai() external; function migrateCUSDCToDUSDC() external; function getBalances() external view returns ( uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns zero ); function getUserSigningKey() external view returns (address userSigningKey); function getNonce() external view returns (uint256 nonce); function getNextCustomActionID( ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getCustomActionID( ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getVersion() external pure returns (uint256 version); } interface DharmaSmartWalletImplementationV8Interface { function tradeEthForDaiAndMintDDai( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData); function getNextEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID); function getEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID); } interface DharmaSmartWalletImplementationV12Interface { function setApproval(address token, uint256 amount) external; } interface DharmaSmartWalletImplementationV13Interface { function redeemAllDDai() external; function redeemAllDUSDC() external; } interface ERC20Interface { function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); } interface ERC1271Interface { function isValidSignature( bytes calldata data, bytes calldata signature ) external view returns (bytes4 magicValue); } interface DTokenInterface { // These external functions trigger accrual on the dToken and backing cToken. function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); // These external functions only trigger accrual on the dToken. function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); // View and pure functions do not trigger accrual on the dToken or the cToken. function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance); } interface DharmaKeyRegistryInterface { function getKey() external view returns (address key); } interface DharmaEscapeHatchRegistryInterface { function setEscapeHatch(address newEscapeHatch) external; function removeEscapeHatch() external; function permanentlyDisableEscapeHatch() external; function getEscapeHatch() external view returns ( bool exists, address escapeHatch ); } interface RevertReasonHelperInterface { function reason(uint256 code) external pure returns (string memory); } interface EtherizedInterface { function triggerEtherTransfer( address payable target, uint256 value ) external returns (bool success); } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } library ECDSA { function recover( bytes32 hash, bytes memory signature ) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(hash, v, r, s); } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } contract Etherized is EtherizedInterface { address private constant _ETHERIZER = address( 0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191 ); function triggerEtherTransfer( address payable target, uint256 amount ) external returns (bool success) { require(msg.sender == _ETHERIZER, "Etherized: only callable by Etherizer"); (success, ) = target.call.value(amount)(""); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } /** * @title DharmaSmartWalletImplementationV14 * @author 0age * @notice The V14 implementation for the Dharma smart wallet is a non-custodial, * meta-transaction-enabled wallet with helper functions to facilitate lending * funds through Dharma Dai and Dharma USD Coin (which in turn use CompoundV2), * and with an added security backstop provided by Dharma Labs prior to making * withdrawals. It adds support for Dharma Dai and Dharma USD Coin - they employ * the respective cTokens as backing tokens and mint and redeem them internally * as interest-bearing collateral. This implementation also contains methods to * support account recovery, escape hatch functionality, and generic actions, * including in an atomic batch. The smart wallet instances utilizing this * implementation are deployed through the Dharma Smart Wallet Factory via * `CREATE2`, which allows for their address to be known ahead of time, and any * Dai or USDC that has already been sent into that address will automatically * be deposited into the respective Dharma Token upon deployment of the new * smart wallet instance. V14 allows for Ether transfers as part of generic * actions, supports "simulation" of generic batch actions, and revises escape * hatch functionality to support arbitrary token withdrawals. */ contract DharmaSmartWalletImplementationV14 is DharmaSmartWalletImplementationV1Interface, DharmaSmartWalletImplementationV3Interface, DharmaSmartWalletImplementationV4Interface, DharmaSmartWalletImplementationV7Interface, DharmaSmartWalletImplementationV8Interface, DharmaSmartWalletImplementationV12Interface, DharmaSmartWalletImplementationV13Interface, ERC1271Interface, Etherized { using Address for address; using ECDSA for bytes32; // WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS! // The user signing key associated with this account is in storage slot 0. // It is the core differentiator when it comes to the account in question. address private _userSigningKey; // The nonce associated with this account is in storage slot 1. Every time a // signature is submitted, it must have the appropriate nonce, and once it has // been accepted the nonce will be incremented. uint256 private _nonce; // The self-call context flag is in storage slot 2. Some protected functions // may only be called externally from calls originating from other methods on // this contract, which enables appropriate exception handling on reverts. // Any storage should only be set immediately preceding a self-call and should // be cleared upon entering the protected function being called. bytes4 internal _selfCallContext; // END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE! // The smart wallet version will be used when constructing valid signatures. uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 14; // DharmaKeyRegistryV2 holds a public key for verifying meta-transactions. DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = ( DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52) ); // Account recovery is facilitated using a hard-coded recovery manager, // controlled by Dharma and implementing appropriate timelocks. address internal constant _ACCOUNT_RECOVERY_MANAGER = address( 0x0000000000DfEd903aD76996FC07BF89C0127B1E ); // Users can designate an "escape hatch" account with the ability to sweep any // funds from their smart wallet by using the Dharma Escape Hatch Registry. DharmaEscapeHatchRegistryInterface internal constant _ESCAPE_HATCH_REGISTRY = ( DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8) ); // Interface with dDai and dUSDC contracts. DTokenInterface internal constant _DDAI = DTokenInterface( 0x00000000001876eB1444c986fD502e618c587430 // mainnet ); DTokenInterface internal constant _DUSDC = DTokenInterface( 0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet ); // The "revert reason helper" contains a collection of revert reason strings. RevertReasonHelperInterface internal constant _REVERT_REASON_HELPER = ( RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4) ); // The "Trade Bot" enables limit orders using unordered meta-transactions. address internal constant _TRADE_BOT = address( 0x8bFB7aC05bF9bDC6Bc3a635d4dd209c8Ba39E554 ); // ERC-1271 must return this magic value when `isValidSignature` is called. bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b); // Specify the amount of gas to supply when making Ether transfers. uint256 private constant _ETH_TRANSFER_GAS = 4999; /** * @notice Accept Ether in the fallback. */ function () external payable {} /** * @notice In the initializer, set up the initial user signing key. Note that * this initializer is only callable while the smart wallet instance is still * in the contract creation phase. * @param userSigningKey address The initial user signing key for the smart * wallet. */ function initialize(address userSigningKey) external { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set up the user's signing key and emit a corresponding event. _setUserSigningKey(userSigningKey); } /** * @notice Redeem all Dharma Dai held by this account for Dai. */ function redeemAllDDai() external { _withdrawMaxFromDharmaToken(AssetType.DAI); } /** * @notice Redeem all Dharma USD Coin held by this account for USDC. */ function redeemAllDUSDC() external { _withdrawMaxFromDharmaToken(AssetType.USDC); } /** * @notice This call is no longer supported. */ function repayAndDeposit() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function withdrawDai( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function withdrawUSDC( uint256 amount, address recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { revert("Deprecated."); } /** * @notice Withdraw Ether to a provided recipient address by transferring it * to a recipient. * @param amount uint256 The amount of Ether to withdraw. * @param recipient address The account to transfer the Ether to. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return True if the transfer succeeded, otherwise false. */ function withdrawEther( uint256 amount, address payable recipient, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok) { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.ETHWithdrawal, abi.encode(amount, recipient), minimumActionGas, userSignature, dharmaSignature ); // Ensure that a non-zero amount of Ether has been supplied. if (amount == 0) { revert(_revertReason(4)); } // Ensure that a non-zero recipient has been supplied. if (recipient == address(0)) { revert(_revertReason(1)); } // Attempt to transfer Ether to the recipient and emit an appropriate event. ok = _transferETH(recipient, amount); } /** * @notice Allow a signatory to increment the nonce at any point. The current * nonce needs to be provided as an argument to the signature so as not to * enable griefing attacks. All arguments can be omitted if called directly. * No value is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param signature bytes A signature that resolves to either the public key * set for this account in storage slot zero, `_userSigningKey`, or the public * key returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function cancel( uint256 minimumActionGas, bytes calldata signature ) external { // Get the current nonce. uint256 nonceToCancel = _nonce; // Ensure the caller or the supplied signature is valid and increment nonce. _validateActionAndIncrementNonce( ActionType.Cancel, abi.encode(), minimumActionGas, signature, signature ); // Emit an event to validate that the nonce is no longer valid. emit Cancel(nonceToCancel); } /** * @notice This call is no longer supported. */ function executeAction( address to, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { revert("Deprecated."); } /** * @notice Allow signatory to set a new user signing key. The current nonce * needs to be provided as an argument to the signature so as not to enable * griefing attacks. No value is returned from this function - it will either * succeed or revert. * @param userSigningKey address The new user signing key to set on this smart * wallet. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function setUserSigningKey( address userSigningKey, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.SetUserSigningKey, abi.encode(userSigningKey), minimumActionGas, userSignature, dharmaSignature ); // Set new user signing key on smart wallet and emit a corresponding event. _setUserSigningKey(userSigningKey); } /** * @notice Set a dedicated address as the "escape hatch" account. This account * can then call `escape(address token)` at any point to "sweep" the entire * balance of the token (or Ether given null address) from the smart wallet. * This function call will revert if the smart wallet has previously called * `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch. * No value is returned from this function - it will either succeed or revert. * @param account address The account to set as the escape hatch account. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function setEscapeHatch( address account, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.SetEscapeHatch, abi.encode(account), minimumActionGas, userSignature, dharmaSignature ); // Ensure that an escape hatch account has been provided. if (account == address(0)) { revert(_revertReason(5)); } // Set a new escape hatch for the smart wallet unless it has been disabled. _ESCAPE_HATCH_REGISTRY.setEscapeHatch(account); } /** * @notice Remove the "escape hatch" account if one is currently set. This * function call will revert if the smart wallet has previously called * `permanentlyDisableEscapeHatch` at any point and disabled the escape hatch. * No value is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function removeEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.RemoveEscapeHatch, abi.encode(), minimumActionGas, userSignature, dharmaSignature ); // Remove the escape hatch for the smart wallet if one is currently set. _ESCAPE_HATCH_REGISTRY.removeEscapeHatch(); } /** * @notice Permanently disable the "escape hatch" mechanism for this smart * wallet. This function call will revert if the smart wallet has already * called `permanentlyDisableEscapeHatch` at any point in the past. No value * is returned from this function - it will either succeed or revert. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. */ function permanentlyDisableEscapeHatch( uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external { // Ensure caller and/or supplied signatures are valid and increment nonce. _validateActionAndIncrementNonce( ActionType.DisableEscapeHatch, abi.encode(), minimumActionGas, userSignature, dharmaSignature ); // Permanently disable the escape hatch mechanism for this smart wallet. _ESCAPE_HATCH_REGISTRY.permanentlyDisableEscapeHatch(); } /** * @notice This call is no longer supported. */ function tradeEthForDaiAndMintDDai( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas, bytes calldata userSignature, bytes calldata dharmaSignature ) external returns (bool ok, bytes memory returnData) { revert("Deprecated."); } /** * @notice Allow the designated escape hatch account to redeem and "sweep" * the total token balance or Ether balance (by supplying the null address) * from the smart wallet. The call will revert for any other caller, or if * there is no escape hatch account on this smart wallet. An `Escaped` event * will be emitted. No value is returned from this function - it will either * succeed or revert. */ function escape(address token) external { // Get the escape hatch account, if one exists, for this account. (bool exists, address escapeHatch) = _ESCAPE_HATCH_REGISTRY.getEscapeHatch(); // Ensure that an escape hatch is currently set for this smart wallet. if (!exists) { revert(_revertReason(6)); } // Ensure that the escape hatch account is the caller. if (msg.sender != escapeHatch) { revert(_revertReason(7)); } if (token == address(0)) { // Determine if there is Ether at this address that should be transferred. uint256 balance = address(this).balance; if (balance > 0) { // Attempt to transfer any Ether to caller and emit an appropriate event. _transferETH(msg.sender, balance); } } else { // Attempt to transfer all tokens to the caller. _transferMax(ERC20Interface(address(token)), msg.sender, false); } // Emit an `Escaped` event. emit Escaped(); } /** * @notice Allow the account recovery manager to set a new user signing key on * the smart wallet. The call will revert for any other caller. The account * recovery manager implements a set of controls around the process, including * a timelock and an option to permanently opt out of account recover. No * value is returned from this function - it will either succeed or revert. * @param newUserSigningKey address The new user signing key to set on this * smart wallet. */ function recover(address newUserSigningKey) external { // Only the Account Recovery Manager contract may call this function. if (msg.sender != _ACCOUNT_RECOVERY_MANAGER) { revert(_revertReason(8)); } // Increment nonce to prevent signature reuse should original key be reset. _nonce++; // Set up the user's new dharma key and emit a corresponding event. _setUserSigningKey(newUserSigningKey); } function setApproval(address token, uint256 amount) external { // Only the Trade Bot contract may call this function. if (msg.sender != _TRADE_BOT) { revert("Only the Trade Bot may call this function."); } ERC20Interface(token).approve(_TRADE_BOT, amount); } /** * @notice This call is no longer supported. */ function migrateSaiToDai() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function migrateCSaiToDDai() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function migrateCDaiToDDai() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function migrateCUSDCToDUSDC() external { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getBalances() external view returns ( uint256 daiBalance, uint256 usdcBalance, uint256 etherBalance, uint256 dDaiUnderlyingDaiBalance, uint256 dUsdcUnderlyingUsdcBalance, uint256 dEtherUnderlyingEtherBalance // always returns 0 ) { revert("Deprecated."); } /** * @notice View function for getting the current user signing key for the * smart wallet. * @return The current user signing key. */ function getUserSigningKey() external view returns (address userSigningKey) { userSigningKey = _userSigningKey; } /** * @notice View function for getting the current nonce of the smart wallet. * This nonce is incremented whenever an action is taken that requires a * signature and/or a specific caller. * @return The current nonce. */ function getNonce() external view returns (uint256 nonce) { nonce = _nonce; } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for the corresponding action. Any nonce value * may be supplied, which enables constructing valid message hashes for * multiple future actions ahead of time. * @param action uint8 The type of action, designated by it's index. Valid * custom actions include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextCustomActionID( ActionType action, uint256 amount, address recipient, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( action, _validateCustomActionTypeAndGetArguments(action, amount, recipient), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for the corresponding action. The current nonce * will be used, which means that it will only be valid for the next action * taken. * @param action uint8 The type of action, designated by it's index. Valid * custom actions include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getCustomActionID( ActionType action, uint256 amount, address recipient, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( action, _validateCustomActionTypeAndGetArguments(action, amount, recipient), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice This call is no longer supported. */ function getNextGenericActionID( address to, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getGenericActionID( address to, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getNextEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice This call is no longer supported. */ function getEthForDaiActionID( uint256 ethToSupply, uint256 minimumDaiReceived, address target, bytes calldata data, uint256 nonce, uint256 minimumActionGas ) external view returns (bytes32 actionID) { revert("Deprecated."); } /** * @notice View function that implements ERC-1271 and validates a set of * signatures, one from the owner (using ERC-1271 as well if the user signing * key is a contract) and one from the Dharma Key Registry against the * supplied data. The data must be ABI encoded as (bytes32, bytes), where the * first bytes32 parameter represents the hash digest for validating the * supplied signatures and the second bytes parameter contains context for the * requested validation. The two signatures are packed together, with the one * from Dharma coming first and that from the user coming second - this is so * that, in future versions, multiple user signatures may be supplied if the * associated key ring requires them. * @param data bytes The data used to validate the signature. * @param signatures bytes The two signatures, each 65 bytes - one from the * owner (using ERC-1271 as well if the user signing key is a contract) and * one from the Dharma Key Registry. * @return The 4-byte magic value to signify a valid signature in ERC-1271, if * the signatures are both valid. */ function isValidSignature( bytes calldata data, bytes calldata signatures ) external view returns (bytes4 magicValue) { // Get message hash digest and any additional context from data argument. bytes32 digest; bytes memory context; if (data.length == 32) { digest = abi.decode(data, (bytes32)); } else { if (data.length < 64) { revert(_revertReason(30)); } (digest, context) = abi.decode(data, (bytes32, bytes)); } // Get Dharma signature & user signature from combined signatures argument. if (signatures.length != 130) { revert(_revertReason(11)); } bytes memory signaturesInMemory = signatures; bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signaturesInMemory, 0x20)) s := mload(add(signaturesInMemory, 0x40)) v := byte(0, mload(add(signaturesInMemory, 0x60))) } bytes memory dharmaSignature = abi.encodePacked(r, s, v); assembly { r := mload(add(signaturesInMemory, 0x61)) s := mload(add(signaturesInMemory, 0x81)) v := byte(0, mload(add(signaturesInMemory, 0xa1))) } bytes memory userSignature = abi.encodePacked(r, s, v); // Validate user signature with `SignatureVerification` as the action type. if ( !_validateUserSignature( digest, ActionType.SignatureVerification, context, _userSigningKey, userSignature ) ) { revert(_revertReason(12)); } // Recover Dharma signature against key returned from Dharma Key Registry. if (_getDharmaSigningKey() != digest.recover(dharmaSignature)) { revert(_revertReason(13)); } // Return the ERC-1271 magic value to indicate success. magicValue = _ERC_1271_MAGIC_VALUE; } /** * @notice View function for getting the current Dharma Smart Wallet * implementation contract address set on the upgrade beacon. * @return The current Dharma Smart Wallet implementation contract. */ function getImplementation() external view returns (address implementation) { (bool ok, bytes memory returnData) = address( 0x000000000026750c571ce882B17016557279ADaa ).staticcall(""); require(ok && returnData.length == 32, "Invalid implementation."); implementation = abi.decode(returnData, (address)); } /** * @notice Pure function for getting the current Dharma Smart Wallet version. * @return The current Dharma Smart Wallet version. */ function getVersion() external pure returns (uint256 version) { version = _DHARMA_SMART_WALLET_VERSION; } /** * @notice Perform a series of generic calls to other contracts. If any call * fails during execution, the preceding calls will be rolled back, but their * original return data will still be accessible. Calls that would otherwise * occur after the failed call will not be executed. Note that accounts with * no code may not be specified unless value is included, nor may the smart * wallet itself or the escape hatch registry. In order to increment the nonce * and invalidate the signatures, a call to this function with valid targets, * signatutes, and gas will always succeed. To determine whether each call * made as part of the action was successful or not, either the corresponding * return value or `CallSuccess` and `CallFailure` events can be used - note * that even calls that return a success status will be rolled back unless all * of the calls returned a success status. Finally, note that this function * must currently be implemented as a public function (instead of as an * external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. */ function executeActionWithAtomicBatchCalls( Call[] memory calls, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) public returns (bool[] memory ok, bytes[] memory returnData) { // Ensure that each `to` address is a contract and is not this contract. for (uint256 i = 0; i < calls.length; i++) { if (calls[i].value == 0) { _ensureValidGenericCallTarget(calls[i].to); } } // Ensure caller and/or supplied signatures are valid and increment nonce. (bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce( ActionType.GenericAtomicBatch, abi.encode(calls), minimumActionGas, userSignature, dharmaSignature ); // Note: from this point on, there are no reverts (apart from out-of-gas or // call-depth-exceeded) originating from this contract. However, one of the // calls may revert, in which case the function will return `false`, along // with the revert reason encoded as bytes, and fire an CallFailure event. // Specify length of returned values in order to work with them in memory. ok = new bool[](calls.length); returnData = new bytes[](calls.length); // Set self-call context to call _executeActionWithAtomicBatchCallsAtomic. _selfCallContext = this.executeActionWithAtomicBatchCalls.selector; // Make the atomic self-call - if any call fails, calls that preceded it // will be rolled back and calls that follow it will not be made. (bool externalOk, bytes memory rawCallResults) = address(this).call( abi.encodeWithSelector( this._executeActionWithAtomicBatchCallsAtomic.selector, calls ) ); // Ensure that self-call context has been cleared. if (!externalOk) { delete _selfCallContext; } // Parse data returned from self-call into each call result and store / log. CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[])); for (uint256 i = 0; i < callResults.length; i++) { Call memory currentCall = calls[i]; // Set the status and the return data / revert reason from the call. ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData; // Emit CallSuccess or CallFailure event based on the outcome of the call. if (callResults[i].ok) { // Note: while the call succeeded, the action may still have "failed". emit CallSuccess( actionID, !externalOk, // If another call failed this will have been rolled back nonce, currentCall.to, uint256(currentCall.value), currentCall.data, callResults[i].returnData ); } else { // Note: while the call failed, the nonce will still be incremented, // which will invalidate all supplied signatures. emit CallFailure( actionID, nonce, currentCall.to, uint256(currentCall.value), currentCall.data, _decodeRevertReason(callResults[i].returnData) ); // exit early - any calls after the first failed call will not execute. break; } } } /** * @notice Protected function that can only be called from * `executeActionWithAtomicBatchCalls` on this contract. It will attempt to * perform each specified call, populating the array of results as it goes, * unless a failure occurs, at which point it will revert and "return" the * array of results as revert data. Otherwise, it will simply return the array * upon successful completion of each call. Finally, note that this function * must currently be implemented as a public function (instead of as an * external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. If any of the calls fail, the array will be returned as revert * data. */ function _executeActionWithAtomicBatchCallsAtomic( Call[] memory calls ) public returns (CallReturn[] memory callResults) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector); bool rollBack = false; callResults = new CallReturn[](calls.length); for (uint256 i = 0; i < calls.length; i++) { // Perform low-level call and set return values using result. (bool ok, bytes memory returnData) = calls[i].to.call.value( uint256(calls[i].value) )(calls[i].data); callResults[i] = CallReturn({ok: ok, returnData: returnData}); if (!ok) { // Exit early - any calls after the first failed call will not execute. rollBack = true; break; } } if (rollBack) { // Wrap in length encoding and revert (provide bytes instead of a string). bytes memory callResultsBytes = abi.encode(callResults); assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) } } } /** * @notice Simulate a series of generic calls to other contracts. Signatures * are not required, but all calls will be rolled back (and calls will only be * simulated up until a failing call is encountered). * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. */ function simulateActionWithAtomicBatchCalls( Call[] memory calls ) public /* view */ returns (bool[] memory ok, bytes[] memory returnData) { // Ensure that each `to` address is a contract and is not this contract. for (uint256 i = 0; i < calls.length; i++) { if (calls[i].value == 0) { _ensureValidGenericCallTarget(calls[i].to); } } // Specify length of returned values in order to work with them in memory. ok = new bool[](calls.length); returnData = new bytes[](calls.length); // Set self-call context to call _simulateActionWithAtomicBatchCallsAtomic. _selfCallContext = this.simulateActionWithAtomicBatchCalls.selector; // Make the atomic self-call - if any call fails, calls that preceded it // will be rolled back and calls that follow it will not be made. (bool mustBeFalse, bytes memory rawCallResults) = address(this).call( abi.encodeWithSelector( this._simulateActionWithAtomicBatchCallsAtomic.selector, calls ) ); // Note: this should never be the case, but check just to be extra safe. if (mustBeFalse) { revert("Simulation call must revert!"); } // Ensure that self-call context has been cleared. delete _selfCallContext; // Parse data returned from self-call into each call result and store / log. CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[])); for (uint256 i = 0; i < callResults.length; i++) { // Set the status and the return data / revert reason from the call. ok[i] = callResults[i].ok; returnData[i] = callResults[i].returnData; if (!callResults[i].ok) { // exit early - any calls after the first failed call will not execute. break; } } } /** * @notice Protected function that can only be called from * `simulateActionWithAtomicBatchCalls` on this contract. It will attempt to * perform each specified call, populating the array of results as it goes, * unless a failure occurs, at which point it will revert and "return" the * array of results as revert data. Regardless, it will roll back all calls at * the end of execution — in other words, this call always reverts. * @param calls Call[] A struct containing the target, value, and calldata to * provide when making each call. * @return An array of structs signifying the status of each call, as well as * any data returned from that call. Calls that are not executed will return * empty data. If any of the calls fail, the array will be returned as revert * data. */ function _simulateActionWithAtomicBatchCallsAtomic( Call[] memory calls ) public returns (CallReturn[] memory callResults) { // Ensure caller is this contract and self-call context is correctly set. _enforceSelfCallFrom(this.simulateActionWithAtomicBatchCalls.selector); callResults = new CallReturn[](calls.length); for (uint256 i = 0; i < calls.length; i++) { // Perform low-level call and set return values using result. (bool ok, bytes memory returnData) = calls[i].to.call.value( uint256(calls[i].value) )(calls[i].data); callResults[i] = CallReturn({ok: ok, returnData: returnData}); if (!ok) { // Exit early - any calls after the first failed call will not execute. break; } } // Wrap in length encoding and revert (provide bytes instead of a string). bytes memory callResultsBytes = abi.encode(callResults); assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) } } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for a given generic atomic batch action. The * current nonce will be used, which means that it will only be valid for the * next action taken. Finally, note that this function must currently be * implemented as a public function (instead of as an external one) due to an * ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getNextGenericAtomicBatchActionID( Call[] memory calls, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.GenericAtomicBatch, abi.encode(calls), _nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice View function that, given an action type and arguments, will return * the action ID or message hash that will need to be prefixed (according to * EIP-191 0x45), hashed, and signed by both the user signing key and by the * key returned for this smart wallet by the Dharma Key Registry in order to * construct a valid signature for a given generic atomic batch action. Any * nonce value may be supplied, which enables constructing valid message * hashes for multiple future actions ahead of time. Finally, note that this * function must currently be implemented as a public function (instead of as * an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param calls Call[] A struct containing the target and calldata to provide * when making each call. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function getGenericAtomicBatchActionID( Call[] memory calls, uint256 nonce, uint256 minimumActionGas ) public view returns (bytes32 actionID) { // Determine the actionID - this serves as a signature hash for an action. actionID = _getActionID( ActionType.GenericAtomicBatch, abi.encode(calls), nonce, minimumActionGas, _userSigningKey, _getDharmaSigningKey() ); } /** * @notice Internal function for setting a new user signing key. Called by the * initializer, by the `setUserSigningKey` function, and by the `recover` * function. A `NewUserSigningKey` event will also be emitted. * @param userSigningKey address The new user signing key to set on this smart * wallet. */ function _setUserSigningKey(address userSigningKey) internal { // Ensure that a user signing key is set on this smart wallet. if (userSigningKey == address(0)) { revert(_revertReason(14)); } _userSigningKey = userSigningKey; emit NewUserSigningKey(userSigningKey); } /** * @notice Internal function for withdrawing the total underlying asset * balance from the corresponding dToken. Note that the requested balance may * not be currently available on Compound, which will cause the withdrawal to * fail. * @param asset uint256 The asset's ID, either Dai (0) or USDC (1). */ function _withdrawMaxFromDharmaToken(AssetType asset) internal { // Get dToken address for the asset type. (No custom ETH withdrawal action.) address dToken = asset == AssetType.DAI ? address(_DDAI) : address(_DUSDC); // Try to retrieve the current dToken balance for this account. ERC20Interface dTokenBalance; (bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector( dTokenBalance.balanceOf.selector, address(this) )); uint256 redeemAmount = 0; if (ok && data.length == 32) { redeemAmount = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check - log an ExternalError. _checkDharmaTokenInteractionAndLogAnyErrors( asset, dTokenBalance.balanceOf.selector, ok, data ); } // Only perform the call to redeem if there is a non-zero balance. if (redeemAmount > 0) { // Attempt to redeem the underlying balance from the dToken contract. (ok, data) = dToken.call(abi.encodeWithSelector( // Function selector is the same for all dTokens, so just use dDai's. _DDAI.redeem.selector, redeemAmount )); // Log an external error if something went wrong with the attempt. _checkDharmaTokenInteractionAndLogAnyErrors( asset, _DDAI.redeem.selector, ok, data ); } } /** * @notice Internal function for transferring the total underlying balance of * the corresponding token to a designated recipient. It will return true if * tokens were successfully transferred (or there is no balance), signified by * the boolean returned by the transfer function, or the call status if the * `suppressRevert` boolean is set to true. * @param token IERC20 The interface of the token in question. * @param recipient address The account that will receive the tokens. * @param suppressRevert bool A boolean indicating whether reverts should be * suppressed or not. Used by the escape hatch so that a problematic transfer * will not block the rest of the call from executing. * @return True if tokens were successfully transferred or if there is no * balance, else false. */ function _transferMax( ERC20Interface token, address recipient, bool suppressRevert ) internal returns (bool success) { // Get the current balance on the smart wallet for the supplied ERC20 token. uint256 balance = 0; bool balanceCheckWorked = true; if (!suppressRevert) { balance = token.balanceOf(address(this)); } else { // Try to retrieve current token balance for this account with 1/2 gas. (bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.balanceOf.selector, address(this)) ); if (ok && data.length >= 32) { balance = abi.decode(data, (uint256)); } else { // Something went wrong with the balance check. balanceCheckWorked = false; } } // Only perform the call to transfer if there is a non-zero balance. if (balance > 0) { if (!suppressRevert) { // Perform the transfer and pass along the returned boolean (or revert). success = token.transfer(recipient, balance); } else { // Attempt transfer with 1/2 gas, allow reverts, and return call status. (success, ) = address(token).call.gas(gasleft() / 2)( abi.encodeWithSelector(token.transfer.selector, recipient, balance) ); } } else { // Skip the transfer and return true as long as the balance check worked. success = balanceCheckWorked; } } /** * @notice Internal function for transferring Ether to a designated recipient. * It will return true and emit an `EthWithdrawal` event if Ether was * successfully transferred - otherwise, it will return false and emit an * `ExternalError` event. * @param recipient address payable The account that will receive the Ether. * @param amount uint256 The amount of Ether to transfer. * @return True if Ether was successfully transferred, else false. */ function _transferETH( address payable recipient, uint256 amount ) internal returns (bool success) { // Attempt to transfer any Ether to caller and emit an event if it fails. (success, ) = recipient.call.gas(_ETH_TRANSFER_GAS).value(amount)(""); if (!success) { emit ExternalError(recipient, _revertReason(18)); } else { emit EthWithdrawal(amount, recipient); } } /** * @notice Internal function for validating supplied gas (if specified), * retrieving the signer's public key from the Dharma Key Registry, deriving * the action ID, validating the provided caller and/or signatures using that * action ID, and incrementing the nonce. This function serves as the * entrypoint for all protected "actions" on the smart wallet, and is the only * area where these functions should revert (other than due to out-of-gas * errors, which can be guarded against by supplying a minimum action gas * requirement). * @param action uint8 The type of action, designated by it's index. Valid * actions include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. A unique hash returned from `getCustomActionID` is prefixed * and hashed to create the message hash for the signature. * @param dharmaSignature bytes A signature that resolves to the public key * returned for this account from the Dharma Key Registry. A unique hash * returned from `getCustomActionID` is prefixed and hashed to create the * signed message. * @return The nonce of the current action (prior to incrementing it). */ function _validateActionAndIncrementNonce( ActionType action, bytes memory arguments, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) internal returns (bytes32 actionID, uint256 actionNonce) { // Ensure that the current gas exceeds the minimum required action gas. // This prevents griefing attacks where an attacker can invalidate a // signature without providing enough gas for the action to succeed. Also // note that some gas will be spent before this check is reached - supplying // ~30,000 additional gas should suffice when submitting transactions. To // skip this requirement, supply zero for the minimumActionGas argument. if (minimumActionGas != 0) { if (gasleft() < minimumActionGas) { revert(_revertReason(19)); } } // Get the current nonce for the action to be performed. actionNonce = _nonce; // Get the user signing key that will be used to verify their signature. address userSigningKey = _userSigningKey; // Get the Dharma signing key that will be used to verify their signature. address dharmaSigningKey = _getDharmaSigningKey(); // Determine the actionID - this serves as the signature hash. actionID = _getActionID( action, arguments, actionNonce, minimumActionGas, userSigningKey, dharmaSigningKey ); // Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID. bytes32 messageHash = actionID.toEthSignedMessageHash(); // Actions other than Cancel require both signatures; Cancel only needs one. if (action != ActionType.Cancel) { // Validate user signing key signature unless it is `msg.sender`. if (msg.sender != userSigningKey) { if ( !_validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_revertReason(20)); } } // Validate Dharma signing key signature unless it is `msg.sender`. if (msg.sender != dharmaSigningKey) { if (dharmaSigningKey != messageHash.recover(dharmaSignature)) { revert(_revertReason(21)); } } } else { // Validate signing key signature unless user or Dharma is `msg.sender`. if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) { if ( dharmaSigningKey != messageHash.recover(dharmaSignature) && !_validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_revertReason(22)); } } } // Increment nonce in order to prevent reuse of signatures after the call. _nonce++; } /** * @notice Internal function to determine whether a call to a given dToken * succeeded, and to emit a relevant ExternalError event if it failed. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param functionSelector bytes4 The function selector that was called on the * corresponding dToken of the asset type. * @param ok bool A boolean representing whether the call returned or * reverted. * @param data bytes The data provided by the returned or reverted call. * @return True if the interaction was successful, otherwise false. This will * be used to determine if subsequent steps in the action should be attempted * or not, specifically a transfer following a withdrawal. */ function _checkDharmaTokenInteractionAndLogAnyErrors( AssetType asset, bytes4 functionSelector, bool ok, bytes memory data ) internal returns (bool success) { // Log an external error if something went wrong with the attempt. if (ok) { if (data.length == 32) { uint256 amount = abi.decode(data, (uint256)); if (amount > 0) { success = true; } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave no tokens calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); emit ExternalError( account, string( abi.encodePacked( name, " gave bad data calling ", functionName, "." ) ) ); } } else { // Get called contract address, name of contract, and function name. (address account, string memory name, string memory functionName) = ( _getDharmaTokenDetails(asset, functionSelector) ); // Decode the revert reason in the event one was returned. string memory revertReason = _decodeRevertReason(data); emit ExternalError( account, string( abi.encodePacked( name, " reverted calling ", functionName, ": ", revertReason ) ) ); } } /** * @notice Internal function to ensure that protected functions can only be * called from this contract and that they have the appropriate context set. * The self-call context is then cleared. It is used as an additional guard * against reentrancy, especially once generic actions are supported by the * smart wallet in future versions. * @param selfCallContext bytes4 The expected self-call context, equal to the * function selector of the approved calling function. */ function _enforceSelfCallFrom(bytes4 selfCallContext) internal { // Ensure caller is this contract and self-call context is correctly set. if (msg.sender != address(this) || _selfCallContext != selfCallContext) { revert(_revertReason(25)); } // Clear the self-call context. delete _selfCallContext; } /** * @notice Internal view function for validating a user's signature. If the * user's signing key does not have contract code, it will be validated via * ecrecover; otherwise, it will be validated using ERC-1271, passing the * message hash that was signed, the action type, and the arguments as data. * @param messageHash bytes32 The message hash that is signed by the user. It * is derived by prefixing (according to EIP-191 0x45) and hashing an actionID * returned from `getCustomActionID`. * @param action uint8 The type of action, designated by it's index. Valid * actions include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param userSignature bytes A signature that resolves to the public key * set for this account in storage slot zero, `_userSigningKey`. If the user * signing key is not a contract, ecrecover will be used; otherwise, ERC1271 * will be used. * @return A boolean representing the validity of the supplied user signature. */ function _validateUserSignature( bytes32 messageHash, ActionType action, bytes memory arguments, address userSigningKey, bytes memory userSignature ) internal view returns (bool valid) { if (!userSigningKey.isContract()) { valid = userSigningKey == messageHash.recover(userSignature); } else { bytes memory data = abi.encode(messageHash, action, arguments); valid = ( ERC1271Interface(userSigningKey).isValidSignature( data, userSignature ) == _ERC_1271_MAGIC_VALUE ); } } /** * @notice Internal view function to get the Dharma signing key for the smart * wallet from the Dharma Key Registry. This key can be set for each specific * smart wallet - if none has been set, a global fallback key will be used. * @return The address of the Dharma signing key, or public key corresponding * to the secondary signer. */ function _getDharmaSigningKey() internal view returns ( address dharmaSigningKey ) { dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey(); } /** * @notice Internal view function that, given an action type and arguments, * will return the action ID or message hash that will need to be prefixed * (according to EIP-191 0x45), hashed, and signed by the key designated by * the Dharma Key Registry in order to construct a valid signature for the * corresponding action. The current nonce will be supplied to this function * when reconstructing an action ID during protected function execution based * on the supplied parameters. * @param action uint8 The type of action, designated by it's index. Valid * actions include Cancel (0), SetUserSigningKey (1), Generic (2), * GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), * ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and * DisableEscapeHatch (9). * @param arguments bytes ABI-encoded arguments for the action. * @param nonce uint256 The nonce to use. * @param minimumActionGas uint256 The minimum amount of gas that must be * provided to this call - be aware that additional gas must still be included * to account for the cost of overhead incurred up until the start of this * function call. * @param dharmaSigningKey address The address of the secondary key, or public * key corresponding to the secondary signer. * @return The action ID, which will need to be prefixed, hashed and signed in * order to construct a valid signature. */ function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey ) internal view returns (bytes32 actionID) { // actionID is constructed according to EIP-191-0x45 to prevent replays. actionID = keccak256( abi.encodePacked( address(this), _DHARMA_SMART_WALLET_VERSION, userSigningKey, dharmaSigningKey, nonce, minimumActionGas, action, arguments ) ); } /** * @notice Internal pure function to get the dToken address, it's name, and * the name of the called function, based on a supplied asset type and * function selector. It is used to help construct ExternalError events. * @param asset uint256 The ID of the asset, either Dai (0) or USDC (1). * @param functionSelector bytes4 The function selector that was called on the * corresponding dToken of the asset type. * @return The dToken address, it's name, and the name of the called function. */ function _getDharmaTokenDetails( AssetType asset, bytes4 functionSelector ) internal pure returns ( address account, string memory name, string memory functionName ) { if (asset == AssetType.DAI) { account = address(_DDAI); name = "Dharma Dai"; } else { account = address(_DUSDC); name = "Dharma USD Coin"; } // Note: since both dTokens have the same interface, just use dDai's. if (functionSelector == _DDAI.mint.selector) { functionName = "mint"; } else { if (functionSelector == ERC20Interface(account).balanceOf.selector) { functionName = "balanceOf"; } else { functionName = string(abi.encodePacked( "redeem", functionSelector == _DDAI.redeem.selector ? "" : "Underlying" )); } } } /** * @notice Internal view function to ensure that a given `to` address provided * as part of a generic action is valid. Calls cannot be performed to accounts * without code or back into the smart wallet itself. Additionally, generic * calls cannot supply the address of the Dharma Escape Hatch registry - the * specific, designated functions must be used in order to make calls into it. * @param to address The address that will be targeted by the generic call. */ function _ensureValidGenericCallTarget(address to) internal view { if (!to.isContract()) { revert(_revertReason(26)); } if (to == address(this)) { revert(_revertReason(27)); } if (to == address(_ESCAPE_HATCH_REGISTRY)) { revert(_revertReason(28)); } } /** * @notice Internal pure function to ensure that a given action type is a * "custom" action type (i.e. is not a generic action type) and to construct * the "arguments" input to an actionID based on that action type. * @param action uint8 The type of action, designated by it's index. Valid * custom actions include Cancel (0), SetUserSigningKey (1), * DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), * SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). * @param amount uint256 The amount to withdraw for Withdrawal actions. This * value is ignored for all non-withdrawal action types. * @param recipient address The account to transfer withdrawn funds to or the * new user signing key. This value is ignored for Cancel, RemoveEscapeHatch, * and DisableEscapeHatch action types. * @return A bytes array containing the arguments that will be provided as * a component of the inputs when constructing a custom action ID. */ function _validateCustomActionTypeAndGetArguments( ActionType action, uint256 amount, address recipient ) internal pure returns (bytes memory arguments) { // Ensure that the action type is a valid custom action type. bool validActionType = ( action == ActionType.Cancel || action == ActionType.SetUserSigningKey || action == ActionType.DAIWithdrawal || action == ActionType.USDCWithdrawal || action == ActionType.ETHWithdrawal || action == ActionType.SetEscapeHatch || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ); if (!validActionType) { revert(_revertReason(29)); } // Use action type to determine parameters to include in returned arguments. if ( action == ActionType.Cancel || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch ) { // Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch. arguments = abi.encode(); } else if ( action == ActionType.SetUserSigningKey || action == ActionType.SetEscapeHatch ) { // Ignore `amount` parameter for other, non-withdrawal actions. arguments = abi.encode(recipient); } else { // Use both `amount` and `recipient` parameters for withdrawals. arguments = abi.encode(amount, recipient); } } /** * @notice Internal pure function to decode revert reasons. The revert reason * prefix is removed and the remaining string argument is decoded. * @param revertData bytes The raw data supplied alongside the revert. * @return The decoded revert reason string. */ function _decodeRevertReason( bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08) && revertData[1] == byte(0xc3) && revertData[2] == byte(0x79) && revertData[3] == byte(0xa0) ) { // Get the revert reason without the prefix from the revert data. bytes memory revertReasonBytes = new bytes(revertData.length - 4); for (uint256 i = 4; i < revertData.length; i++) { revertReasonBytes[i - 4] = revertData[i]; } // Decode the resultant revert reason as a string. revertReason = abi.decode(revertReasonBytes, (string)); } else { // Simply return the default, with no revert reason. revertReason = _revertReason(uint256(-1)); } } /** * @notice Internal pure function call the revert reason helper contract, * supplying a revert "code" and receiving back a revert reason string. * @param code uint256 The code for the revert reason. * @return The revert reason string. */ function _revertReason( uint256 code ) internal pure returns (string memory reason) { reason = _REVERT_REASON_HELPER.reason(code); } }
Internal function for validating supplied gas (if specified), retrieving the signer's public key from the Dharma Key Registry, deriving the action ID, validating the provided caller and/or signatures using that action ID, and incrementing the nonce. This function serves as the entrypoint for all protected "actions" on the smart wallet, and is the only area where these functions should revert (other than due to out-of-gas errors, which can be guarded against by supplying a minimum action gas requirement). action uint8 The type of action, designated by it's index. Valid actions include Cancel (0), SetUserSigningKey (1), Generic (2), GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5), ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), and DisableEscapeHatch (9). arguments bytes ABI-encoded arguments for the action. minimumActionGas uint256 The minimum amount of gas that must be provided to this call - be aware that additional gas must still be included to account for the cost of overhead incurred up until the start of this function call. userSignature bytes A signature that resolves to the public key set for this account in storage slot zero, `_userSigningKey`. If the user signing key is not a contract, ecrecover will be used; otherwise, ERC1271 will be used. A unique hash returned from `getCustomActionID` is prefixed and hashed to create the message hash for the signature. dharmaSignature bytes A signature that resolves to the public key returned for this account from the Dharma Key Registry. A unique hash returned from `getCustomActionID` is prefixed and hashed to create the signed message. return The nonce of the current action (prior to incrementing it)./ Ensure that the current gas exceeds the minimum required action gas. This prevents griefing attacks where an attacker can invalidate a signature without providing enough gas for the action to succeed. Also note that some gas will be spent before this check is reached - supplying ~30,000 additional gas should suffice when submitting transactions. To skip this requirement, supply zero for the minimumActionGas argument. Actions other than Cancel require both signatures; Cancel only needs one. Validate user signing key signature unless it is `msg.sender`. Validate Dharma signing key signature unless it is `msg.sender`. Validate signing key signature unless user or Dharma is `msg.sender`.
function _validateActionAndIncrementNonce( ActionType action, bytes memory arguments, uint256 minimumActionGas, bytes memory userSignature, bytes memory dharmaSignature ) internal returns (bytes32 actionID, uint256 actionNonce) { if (minimumActionGas != 0) { if (gasleft() < minimumActionGas) { revert(_revertReason(19)); } } action, arguments, actionNonce, minimumActionGas, userSigningKey, dharmaSigningKey ); if (action != ActionType.Cancel) { if (msg.sender != userSigningKey) { if ( !_validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_revertReason(20)); } } if (msg.sender != dharmaSigningKey) { if (dharmaSigningKey != messageHash.recover(dharmaSignature)) { revert(_revertReason(21)); } } if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) { if ( dharmaSigningKey != messageHash.recover(dharmaSignature) && !_validateUserSignature( messageHash, action, arguments, userSigningKey, userSignature ) ) { revert(_revertReason(22)); } } } }
2,135,598
./full_match/42220/0x9f5c71eaFeFC910edcC26CD796ccD20165CC14b9/sources/project_/contracts/interfaces/uniswap/TickBitmap.sol
Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either to the left (less than or equal to) or right (greater than) of the given tick pool The mapping in which to compute the next initialized tick tick The starting tick tickSpacing The spacing between usable ticks lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) return next The next initialized or uninitialized tick up to 256 ticks away from the current tick return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks all the 1s at or to the right of the current bitPos if there are no initialized ticks to the right of or at the current tick, return rightmost in the word overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick start from the word of the next tick, since the current tick state doesn't matter all the 1s at or to the left of the bitPos if there are no initialized ticks to the left of the current tick, return leftmost in the word overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
function nextInitializedTickWithinOneWord( IUniswapV3PoolState pool, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { int24 compressed = tick / tickSpacing; if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = pool.tickBitmap(wordPos) & mask; initialized = masked != 0; next = initialized ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing : (compressed - int24(bitPos)) * tickSpacing; (int16 wordPos, uint8 bitPos) = position(compressed + 1); uint256 mask = ~((1 << bitPos) - 1); uint256 masked = pool.tickBitmap(wordPos) & mask; initialized = masked != 0; next = initialized ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing; } }
16,322,901
./full_match/1/0xD44Cf4175a6f58E78c8eBF1149285C92f60B7C2d/sources/contracts/vesting/CBSNVesting.sol
Available output is based on BSN unlocking linearly
function _isOutputAmountAvailable(uint256 _outputAmount) internal override view returns (bool) { if (_outputAmount == 0) { return false; } return BSNAvailableForClaim() >= _outputAmount; }
9,783,267
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "./WeightedStaking.sol"; import "./IStaking.sol"; import "../../rsk/RSKAddrValidator.sol"; import "../Vesting/ITeamVesting.sol"; import "../ApprovalReceiver.sol"; /** * @title Staking contract. * @notice Pay-in and pay-out function for staking and withdrawing tokens. * Staking is delegated and vested: To gain voting power, SOV holders must * stake their SOV for a given period of time. Aside from Bitocracy * participation, there's a financially-rewarding reason for staking SOV. * Tokenholders who stake their SOV receive staking rewards, a pro-rata share * of the revenue that the platform generates from various transaction fees * plus revenues from stakers who have a portion of their SOV slashed for * early unstaking. * */ contract Staking is IStaking, WeightedStaking, ApprovalReceiver { /** * @notice Stake the given amount for the given duration of time. * @param amount The number of tokens to stake. * @param until Timestamp indicating the date until which to stake. * @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. * @param delegatee The address of the delegatee or 0x0 if there is none. * */ function stake( uint96 amount, uint256 until, address stakeFor, address delegatee ) external { _stake(msg.sender, amount, until, stakeFor, delegatee, false); } /** * @notice Stake the given amount for the given duration of time. * @dev This function will be invoked from receiveApproval * @dev SOV.approveAndCall -> this.receiveApproval -> this.stakeWithApproval * @param sender The sender of SOV.approveAndCall * @param amount The number of tokens to stake. * @param until Timestamp indicating the date until which to stake. * @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. * @param delegatee The address of the delegatee or 0x0 if there is none. * */ function stakeWithApproval( address sender, uint96 amount, uint256 until, address stakeFor, address delegatee ) public onlyThisContract { _stake(sender, amount, until, stakeFor, delegatee, false); } /** * @notice Send sender's tokens to this contract and update its staked balance. * @param sender The sender of the tokens. * @param amount The number of tokens to send. * @param until The date until which the tokens will be staked. * @param stakeFor The beneficiary whose stake will be increased. * @param delegatee The address of the delegatee or stakeFor if default 0x0. * @param timeAdjusted Whether fixing date to stacking periods or not. * */ function _stake( address sender, uint96 amount, uint256 until, address stakeFor, address delegatee, bool timeAdjusted ) internal { require(amount > 0, "Staking::stake: amount of tokens to stake needs to be bigger than 0"); if (!timeAdjusted) { until = timestampToLockDate(until); } require(until > block.timestamp, "Staking::timestampToLockDate: staking period too short"); /// @dev Stake for the sender if not specified otherwise. if (stakeFor == address(0)) { stakeFor = sender; } /// @dev Delegate for stakeFor if not specified otherwise. if (delegatee == address(0)) { delegatee = stakeFor; } /// @dev Do not stake longer than the max duration. if (!timeAdjusted) { uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION); if (until > latest) until = latest; } uint96 previousBalance = currentBalance(stakeFor, until); /// @dev Increase stake. _increaseStake(sender, amount, stakeFor, until); if (previousBalance == 0) { /// @dev Regular delegation if it's a first stake. _delegate(stakeFor, delegatee, until); } else { address previousDelegatee = delegates[stakeFor][until]; if (previousDelegatee != delegatee) { /// @dev Update delegatee. delegates[stakeFor][until] = delegatee; /// @dev Decrease stake on previous balance for previous delegatee. _decreaseDelegateStake(previousDelegatee, until, previousBalance); /// @dev Add previousBalance to amount. amount = add96(previousBalance, amount, "Staking::stake: balance overflow"); } /// @dev Increase stake. _increaseDelegateStake(delegatee, until, amount); } } /** * @notice Extend the staking duration until the specified date. * @param previousLock The old unlocking timestamp. * @param until The new unlocking timestamp in seconds. * */ function extendStakingDuration(uint256 previousLock, uint256 until) public { until = timestampToLockDate(until); require(previousLock <= until, "Staking::extendStakingDuration: cannot reduce the staking duration"); /// @dev Do not exceed the max duration, no overflow possible. uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION); if (until > latest) until = latest; /// @dev Update checkpoints. /// @dev TODO James: Can reading stake at block.number -1 cause trouble with multiple tx in a block? uint96 amount = getPriorUserStakeByDate(msg.sender, previousLock, block.number - 1); require(amount > 0, "Staking::extendStakingDuration: nothing staked until the previous lock date"); _decreaseUserStake(msg.sender, previousLock, amount); _increaseUserStake(msg.sender, until, amount); _decreaseDailyStake(previousLock, amount); _increaseDailyStake(until, amount); /// @dev Delegate might change: if there is already a delegate set for the until date, it will remain the delegate for this position address delegateFrom = delegates[msg.sender][previousLock]; address delegateTo = delegates[msg.sender][until]; if (delegateTo == address(0)) { delegateTo = delegateFrom; delegates[msg.sender][until] = delegateFrom; } delegates[msg.sender][previousLock] = address(0); _decreaseDelegateStake(delegateFrom, previousLock, amount); _increaseDelegateStake(delegateTo, until, amount); emit ExtendedStakingDuration(msg.sender, previousLock, until); } /** * @notice Send sender's tokens to this contract and update its staked balance. * @param sender The sender of the tokens. * @param amount The number of tokens to send. * @param stakeFor The beneficiary whose stake will be increased. * @param until The date until which the tokens will be staked. * */ function _increaseStake( address sender, uint96 amount, address stakeFor, uint256 until ) internal { /// @dev Retrieve the SOV tokens. bool success = SOVToken.transferFrom(sender, address(this), amount); require(success); /// @dev Increase staked balance. uint96 balance = currentBalance(stakeFor, until); balance = add96(balance, amount, "Staking::increaseStake: balance overflow"); /// @dev Update checkpoints. _increaseDailyStake(until, amount); _increaseUserStake(stakeFor, until, amount); emit TokensStaked(stakeFor, amount, until, balance); } /** * @notice Stake tokens according to the vesting schedule. * @param amount The amount of tokens to stake. * @param cliff The time interval to the first withdraw. * @param duration The staking duration. * @param intervalLength The length of each staking interval when cliff passed. * @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. * @param delegatee The address of the delegatee or 0x0 if there is none. * */ function stakesBySchedule( uint256 amount, uint256 cliff, uint256 duration, uint256 intervalLength, address stakeFor, address delegatee ) public { /** * @dev Stake them until lock dates according to the vesting schedule. * Note: because staking is only possible in periods of 2 weeks, * the total duration might end up a bit shorter than specified * depending on the date of staking. * */ uint256 start = timestampToLockDate(block.timestamp + cliff); if (duration > MAX_DURATION) { duration = MAX_DURATION; } uint256 end = timestampToLockDate(block.timestamp + duration); uint256 numIntervals = (end - start) / intervalLength + 1; uint256 stakedPerInterval = amount / numIntervals; /// @dev stakedPerInterval might lose some dust on rounding. Add it to the first staking date. if (numIntervals >= 1) { _stake(msg.sender, uint96(amount - stakedPerInterval * (numIntervals - 1)), start, stakeFor, delegatee, true); } /// @dev Stake the rest in 4 week intervals. for (uint256 i = start + intervalLength; i <= end; i += intervalLength) { /// @dev Stakes for itself, delegates to the owner. _stake(msg.sender, uint96(stakedPerInterval), i, stakeFor, delegatee, true); } } /** * @notice Withdraw the given amount of tokens if they are unlocked. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * */ function withdraw( uint96 amount, uint256 until, address receiver ) public { _withdraw(amount, until, receiver, false); } /** * @notice Withdraw the given amount of tokens. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * @dev Can be invoked only by whitelisted contract passed to governanceWithdrawVesting * */ function governanceWithdraw( uint96 amount, uint256 until, address receiver ) public { require(vestingWhitelist[msg.sender], "unauthorized"); _withdraw(amount, until, receiver, true); } /** * @notice Withdraw tokens for vesting contract. * @param vesting The address of Vesting contract. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * @dev Can be invoked only by whitelisted contract passed to governanceWithdrawVesting. * */ function governanceWithdrawVesting(address vesting, address receiver) public onlyOwner { vestingWhitelist[vesting] = true; ITeamVesting(vesting).governanceWithdrawTokens(receiver); vestingWhitelist[vesting] = false; emit VestingTokensWithdrawn(vesting, receiver); } /** * @notice Send user' staked tokens to a receiver taking into account punishments. * Sovryn encourages long-term commitment and thinking. When/if you unstake before * the end of the staking period, a percentage of the original staking amount will * be slashed. This amount is also added to the reward pool and is distributed * between all other stakers. * * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * @param isGovernance Whether all tokens (true) * or just unlocked tokens (false). * */ function _withdraw( uint96 amount, uint256 until, address receiver, bool isGovernance ) internal { until = _adjustDateForOrigin(until); _validateWithdrawParams(amount, until); /// @dev Determine the receiver. if (receiver == address(0)) receiver = msg.sender; /// @dev Update the checkpoints. _decreaseDailyStake(until, amount); _decreaseUserStake(msg.sender, until, amount); _decreaseDelegateStake(delegates[msg.sender][until], until, amount); /// @dev Early unstaking should be punished. if (block.timestamp < until && !allUnlocked && !isGovernance) { uint96 punishedAmount = _getPunishedAmount(amount, until); amount -= punishedAmount; /// @dev punishedAmount can be 0 if block.timestamp are very close to 'until' if (punishedAmount > 0) { require(address(feeSharing) != address(0), "Staking::withdraw: FeeSharing address wasn't set"); /// @dev Move punished amount to fee sharing. /// @dev Approve transfer here and let feeSharing do transfer and write checkpoint. SOVToken.approve(address(feeSharing), punishedAmount); feeSharing.transferTokens(address(SOVToken), punishedAmount); } } /// @dev transferFrom bool success = SOVToken.transfer(receiver, amount); require(success, "Staking::withdraw: Token transfer failed"); emit TokensWithdrawn(msg.sender, receiver, amount); } /** * @notice Get available and punished amount for withdrawing. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * */ function getWithdrawAmounts(uint96 amount, uint256 until) public view returns (uint96, uint96) { _validateWithdrawParams(amount, until); uint96 punishedAmount = _getPunishedAmount(amount, until); return (amount - punishedAmount, punishedAmount); } /** * @notice Get punished amount for withdrawing. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * */ function _getPunishedAmount(uint96 amount, uint256 until) internal view returns (uint96) { uint256 date = timestampToLockDate(block.timestamp); uint96 weight = computeWeightByDate(until, date); /// @dev (10 - 1) * WEIGHT_FACTOR weight = weight * weightScaling; return (amount * weight) / WEIGHT_FACTOR / 100; } /** * @notice Validate withdraw parameters. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * */ function _validateWithdrawParams(uint96 amount, uint256 until) internal view { require(amount > 0, "Staking::withdraw: amount of tokens to be withdrawn needs to be bigger than 0"); uint96 balance = getPriorUserStakeByDate(msg.sender, until, block.number - 1); require(amount <= balance, "Staking::withdraw: not enough balance"); } /** * @notice Get the current balance of an account locked until a certain date. * @param account The user address. * @param lockDate The lock date. * @return The stake amount. * */ function currentBalance(address account, uint256 lockDate) internal view returns (uint96) { return userStakingCheckpoints[account][lockDate][numUserStakingCheckpoints[account][lockDate] - 1].stake; } /** * @notice Get the number of staked tokens held by the user account. * @dev Iterate checkpoints adding up stakes. * @param account The address of the account to get the balance of. * @return The number of tokens held. * */ function balanceOf(address account) public view returns (uint96 balance) { for (uint256 i = kickoffTS; i <= block.timestamp + MAX_DURATION; i += TWO_WEEKS) { balance = add96(balance, currentBalance(account, i), "Staking::balanceOf: overflow"); } } /** * @notice Delegate votes from `msg.sender` which are locked until lockDate to `delegatee`. * @param delegatee The address to delegate votes to. * @param lockDate the date if the position to delegate. * */ function delegate(address delegatee, uint256 lockDate) public { return _delegate(msg.sender, delegatee, lockDate); } /** * @notice Delegates votes from signatory to a delegatee account. * Voting with EIP-712 Signatures. * * Voting power can be delegated to any address, and then can be used to * vote on proposals. A key benefit to users of by-signature functionality * is that they can create a signed vote transaction for free, and have a * trusted third-party spend rBTC(or ETH) on gas fees and write it to the * blockchain for them. * * The third party in this scenario, submitting the SOV-holder’s signed * transaction holds a voting power that is for only a single proposal. * The signatory still holds the power to vote on their own behalf in * the proposal if the third party has not yet published the signed * transaction that was given to them. * * @dev The signature needs to be broken up into 3 parameters, known as * v, r and s: * const r = '0x' + sig.substring(2).substring(0, 64); * const s = '0x' + sig.substring(2).substring(64, 128); * const v = '0x' + sig.substring(2).substring(128, 130); * * @param delegatee The address to delegate votes to. * @param lockDate The date until which the position is locked. * @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 lockDate, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { /** * @dev The DOMAIN_SEPARATOR is a hash that uniquely identifies a * smart contract. It is built from a string denoting it as an * EIP712 Domain, the name of the token contract, the version, * the chainId in case it changes, and the address that the * contract is deployed at. * */ bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); /// @dev GovernorAlpha uses BALLOT_TYPEHASH, while Staking uses DELEGATION_TYPEHASH bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, lockDate, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); /// @dev Verify address is not null and PK is not null either. require(RSKAddrValidator.checkPKNotZero(signatory), "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::delegateBySig: signature expired"); return _delegate(signatory, delegatee, lockDate); } /** * @notice Get the current votes balance for a user account. * @param account The address to get votes balance. * @dev This is a wrapper to simplify arguments. The actual computation is * performed on WeightedStaking parent contract. * @return The number of current votes for a user account. * */ function getCurrentVotes(address account) external view returns (uint96) { return getPriorVotes(account, block.number - 1, block.timestamp); } /** * @notice Get the current number of tokens staked for a day. * @param lockedTS The timestamp to get the staked tokens for. * */ function getCurrentStakedUntil(uint256 lockedTS) external view returns (uint96) { uint32 nCheckpoints = numTotalStakingCheckpoints[lockedTS]; return nCheckpoints > 0 ? totalStakingCheckpoints[lockedTS][nCheckpoints - 1].stake : 0; } /** * @notice Set new delegatee. Move from user's current delegate to a new * delegatee the stake balance. * @param delegator The user address to move stake balance from its current delegatee. * @param delegatee The new delegatee. The address to move stake balance to. * @param lockedTS The lock date. * */ function _delegate( address delegator, address delegatee, uint256 lockedTS ) internal { address currentDelegate = delegates[delegator][lockedTS]; uint96 delegatorBalance = currentBalance(delegator, lockedTS); delegates[delegator][lockedTS] = delegatee; emit DelegateChanged(delegator, lockedTS, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance, lockedTS); } /** * @notice Move an amount of delegate stake from a source address to a * destination address. * @param srcRep The address to get the staked amount from. * @param dstRep The address to send the staked amount to. * @param amount The staked amount to move. * @param lockedTS The lock date. * */ function _moveDelegates( address srcRep, address dstRep, uint96 amount, uint256 lockedTS ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) _decreaseDelegateStake(srcRep, lockedTS, amount); if (dstRep != address(0)) _increaseDelegateStake(dstRep, lockedTS, amount); } } /** * @notice Retrieve CHAIN_ID of the executing chain. * * Chain identifier (chainID) introduced in EIP-155 protects transaction * included into one chain from being included into another chain. * Basically, chain identifier is an integer number being used in the * processes of signing transactions and verifying transaction signatures. * * @dev As of version 0.5.12, Solidity includes an assembly function * chainid() that provides access to the new CHAINID opcode. * * TODO: chainId is included in block. So you can get chain id like * block timestamp or block number: block.chainid; * */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @notice Allow the owner to set a new staking contract. * As a consequence it allows the stakers to migrate their positions * to the new contract. * @dev Doesn't have any influence as long as migrateToNewStakingContract * is not implemented. * @param _newStakingContract The address of the new staking contract. * */ function setNewStakingContract(address _newStakingContract) public onlyOwner { require(_newStakingContract != address(0), "can't reset the new staking contract to 0"); newStakingContract = _newStakingContract; } /** * @notice Allow the owner to set a fee sharing proxy contract. * We need it for unstaking with slashing. * @param _feeSharing The address of FeeSharingProxy contract. * */ function setFeeSharing(address _feeSharing) public onlyOwner { require(_feeSharing != address(0), "FeeSharing address shouldn't be 0"); feeSharing = IFeeSharingProxy(_feeSharing); } /** * @notice Allow the owner to set weight scaling. * We need it for unstaking with slashing. * @param _weightScaling The weight scaling. * */ function setWeightScaling(uint96 _weightScaling) public onlyOwner { require( MIN_WEIGHT_SCALING <= _weightScaling && _weightScaling <= MAX_WEIGHT_SCALING, "weight scaling doesn't belong to range [1, 9]" ); weightScaling = _weightScaling; } /** * @notice Allow a staker to migrate his positions to the new staking contract. * @dev Staking contract needs to be set before by the owner. * Currently not implemented, just needed for the interface. * In case it's needed at some point in the future, * the implementation needs to be changed first. * */ function migrateToNewStakingContract() public { require(newStakingContract != address(0), "there is no new staking contract set"); /// @dev implementation: /// @dev Iterate over all possible lock dates from now until now + MAX_DURATION. /// @dev Read the stake & delegate of the msg.sender /// @dev If stake > 0, stake it at the new contract until the lock date with the current delegate. } /** * @notice Allow the owner to unlock all tokens in case the staking contract * is going to be replaced * Note: Not reversible on purpose. once unlocked, everything is unlocked. * The owner should not be able to just quickly unlock to withdraw his own * tokens and lock again. * @dev Last resort. * */ function unlockAllTokens() public onlyOwner { allUnlocked = true; emit TokensUnlocked(SOVToken.balanceOf(address(this))); } /** * @notice Get list of stakes for a user account. * @param account The address to get stakes. * @return The arrays of dates and stakes. * */ function getStakes(address account) external view returns (uint256[] memory dates, uint96[] memory stakes) { uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION); /// @dev Calculate stakes. uint256 count = 0; /// @dev We need to iterate from first possible stake date after deployment to the latest from current time. for (uint256 i = kickoffTS + TWO_WEEKS; i <= latest; i += TWO_WEEKS) { if (currentBalance(account, i) > 0) { count++; } } dates = new uint256[](count); stakes = new uint96[](count); /// @dev We need to iterate from first possible stake date after deployment to the latest from current time. uint256 j = 0; for (uint256 i = kickoffTS + TWO_WEEKS; i <= latest; i += TWO_WEEKS) { uint96 balance = currentBalance(account, i); if (balance > 0) { dates[j] = i; stakes[j] = balance; j++; } } } /** * @notice Overrides default ApprovalReceiver._getToken function to * register SOV token on this contract. * @return The address of SOV token. * */ function _getToken() internal view returns (address) { return address(SOVToken); } /** * @notice Overrides default ApprovalReceiver._getSelectors function to * register stakeWithApproval selector on this contract. * @return The array of registered selectors on this contract. * */ function _getSelectors() internal view returns (bytes4[] memory) { bytes4[] memory selectors = new bytes4[](1); selectors[0] = this.stakeWithApproval.selector; return selectors; } }
Allow the owner to set a fee sharing proxy contract. We need it for unstaking with slashing. _feeSharing The address of FeeSharingProxy contract. /
function setFeeSharing(address _feeSharing) public onlyOwner { require(_feeSharing != address(0), "FeeSharing address shouldn't be 0"); feeSharing = IFeeSharingProxy(_feeSharing); }
13,117,487
pragma solidity 0.4.25; contract ParallelConfigPrecompiled { function registerParallelFunctionInternal(address, string, uint256) public returns (int); function unregisterParallelFunctionInternal(address, string) public returns (int); } contract ParallelContract { ParallelConfigPrecompiled precompiled = ParallelConfigPrecompiled(0x1006); function registerParallelFunction(string functionName, uint256 criticalSize) public { precompiled.registerParallelFunctionInternal(address(this), functionName, criticalSize); } function unregisterParallelFunction(string functionName) public { precompiled.unregisterParallelFunctionInternal(address(this), functionName); } function enableParallel() public; function disableParallel() public; } /// @title Exchange - Facilitates exchange of ERC20 tokens. /// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]> contract ExchangeV2 is ParallelContract { // Error Codes enum Errors { ORDER_EXPIRED, // Order has already expired ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled ROUNDING_ERROR_TOO_LARGE, // Rounding error too large INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer } string constant public VERSION = "1.0.0"; uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas address public ZRX_TOKEN_CONTRACT; address public TOKEN_TRANSFER_PROXY_CONTRACT; // Mappings of orderHash => amounts of takerTokenAmount filled or cancelled. mapping (bytes32 => uint) public filled; mapping (bytes32 => uint) public cancelled; mapping(address => uint256) balances; event LogFill( address indexed maker, address taker, address indexed feeRecipient, address makerToken, address takerToken, uint filledMakerTokenAmount, uint filledTakerTokenAmount, uint paidMakerFee, uint paidTakerFee, uint tokens// keccak256(makerToken, takerToken), allows subscribing to a token pair ); event LogCancel( address indexed maker, address indexed feeRecipient, address makerToken, address takerToken, uint cancelledMakerTokenAmount, uint cancelledTakerTokenAmount, bytes32 indexed tokens, bytes32 orderHash ); event LogError(uint8 indexed errorId, bytes32 indexed orderHash); struct Order { address maker; address taker; address feeRecipient; uint makerTokenAmount; uint takerTokenAmount; uint makerFee; uint takerFee; uint expirationTimestampInSec; bytes32 orderHash; } function fillOrder(uint256 fillTakerTokenAmount, address maker, address taker, address feeRecipient, bytes32 orderHash) public { Order memory order = Order({ maker: maker, taker: msg.sender, feeRecipient: feeRecipient, makerTokenAmount: 10000, takerTokenAmount: 10000, makerFee: 1, takerFee: 1, expirationTimestampInSec: 1, orderHash: orderHash }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); if (block.timestamp >= order.expirationTimestampInSec) { //LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); //return 0; } address(0x1007).call.value(0)(); uint remainingTakerTokenAmount = order.takerTokenAmount - getUnavailableTakerTokenAmount(order.orderHash); uint filledTakerTokenAmount = fillTakerTokenAmount < remainingTakerTokenAmount ? fillTakerTokenAmount:remainingTakerTokenAmount; //if (filledTakerTokenAmount == 0) { // LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); // return 0; // } // if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { // LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); // return 0; // } // if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { // LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); // return 0; // } uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = filled[order.orderHash] + filledTakerTokenAmount; // _xend() transferFrom( order.maker, msg.sender, filledMakerTokenAmount ); transferFrom( msg.sender, order.maker, filledTakerTokenAmount ); address(0x1008).call.value(0)(); if (order.feeRecipient != address(0)) { if (order.makerFee > 0) { paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); transferFrom( order.maker, order.feeRecipient, paidMakerFee ); } if (order.takerFee > 0) { paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); transferFrom( msg.sender, order.feeRecipient, paidTakerFee ); } } LogFill( order.maker, msg.sender, order.feeRecipient, 0x01, 0x02, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, 1000 ); } function fillOrder_2(uint256 fillTakerTokenAmount, address maker, address taker, address feeRecipient, bytes32 orderHash) public { Order memory order = Order({ maker: maker, taker: msg.sender, feeRecipient: feeRecipient, makerTokenAmount: 10000, takerTokenAmount: 10000, makerFee: 1, takerFee: 1, expirationTimestampInSec: 1, orderHash: orderHash }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); if (block.timestamp >= order.expirationTimestampInSec) { //LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); //return 0; } // _xbegin() uint remainingTakerTokenAmount = order.takerTokenAmount - getUnavailableTakerTokenAmount(order.orderHash); uint filledTakerTokenAmount = fillTakerTokenAmount < remainingTakerTokenAmount ? fillTakerTokenAmount:remainingTakerTokenAmount; //if (filledTakerTokenAmount == 0) { // LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); // return 0; // } // if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { // LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); // return 0; // } // if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { // LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); // return 0; // } uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = filled[order.orderHash] + filledTakerTokenAmount; // _xend() transferFrom( order.maker, msg.sender, filledMakerTokenAmount ); transferFrom( msg.sender, order.maker, filledTakerTokenAmount ); if (order.feeRecipient != address(0)) { if (order.makerFee > 0) { paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); transferFrom( order.maker, order.feeRecipient, paidMakerFee ); } if (order.takerFee > 0) { paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); transferFrom( msg.sender, order.feeRecipient, paidTakerFee ); } } LogFill( order.maker, msg.sender, order.feeRecipient, 0x01, 0x02, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, 1000 ); } function fillOrder_1(address maker, address taker, address feeRecipient, uint256 fillTakerTokenAmount, bytes32 orderHash) public { Order memory order = Order({ maker: maker, taker: msg.sender, feeRecipient: feeRecipient, makerTokenAmount: 10000, takerTokenAmount: 10000, makerFee: 1, takerFee: 1, expirationTimestampInSec: 1, orderHash: orderHash }); require(order.taker == address(0) || order.taker == msg.sender); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0); if (block.timestamp >= order.expirationTimestampInSec) { //LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash); //return 0; } // _xbegin() uint remainingTakerTokenAmount = order.takerTokenAmount - getUnavailableTakerTokenAmount(order.orderHash); uint filledTakerTokenAmount = fillTakerTokenAmount < remainingTakerTokenAmount ? fillTakerTokenAmount:remainingTakerTokenAmount; //if (filledTakerTokenAmount == 0) { // LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash); // return 0; // } // if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) { // LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash); // return 0; // } // if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) { // LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash); // return 0; // } uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount); uint paidMakerFee; uint paidTakerFee; filled[order.orderHash] = filled[order.orderHash] + filledTakerTokenAmount; // _xend() transferFrom( order.maker, msg.sender, filledMakerTokenAmount ); transferFrom( msg.sender, order.maker, filledTakerTokenAmount ); if (order.feeRecipient != address(0)) { if (order.makerFee > 0) { paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee); transferFrom( order.maker, order.feeRecipient, paidMakerFee ); } if (order.takerFee > 0) { paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee); transferFrom( msg.sender, order.feeRecipient, paidTakerFee ); } } LogFill( order.maker, msg.sender, order.feeRecipient, 0x01, 0x02, filledMakerTokenAmount, filledTakerTokenAmount, paidMakerFee, paidTakerFee, 1000 ); } function getPartialAmount(uint numerator, uint denominator, uint target) public constant returns (uint) { return (numerator*target)/denominator; } function getUnavailableTakerTokenAmount(bytes32 orderHash) public constant returns (uint) { return filled[orderHash] + cancelled[orderHash]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transferFrom(address from, address to, uint256 tokens) public { balances[from] = balances[from] - tokens; balances[to] = balances[to] + tokens; } function transfer(uint256 token, address to) { for (int i=0; i<100; i++) {} balances[to] = token; } function set(uint token) { balances[msg.sender] = token; } function enableParallel() public { // critical number is to define how many critical params from start registerParallelFunction("fillOrder(uint256,address,address,address,bytes32)", 1); // critical: string string registerParallelFunction("transfer(uint256,address)", 1); // critical: string registerParallelFunction("fillOrder_1(address,address,address,uint256,bytes32)", 2); registerParallelFunction("fillOrder_2(uint256,address,address,address,bytes32)", 1); // critical: string string } // Disable register parallel function function disableParallel() public { unregisterParallelFunction("fillOrder(address, address, address, address, address, uint, uint, uint, uint,uint,uint,bool, bytes32)"); } }
critical number is to define how many critical params from start critical: string string
function enableParallel() public { registerParallelFunction("fillOrder_1(address,address,address,uint256,bytes32)", 2); registerParallelFunction("fillOrder_2(uint256,address,address,address,bytes32)", 1); }
14,069,794
./partial_match/1313161554/0x4D239DB5b81389330cc6e2890D1d98b93451A25D/sources/_contracts/ReaperStrategyBastionLP.sol
Withdraws funds and sends them back to the vault./
function _withdraw(uint256 _amount) internal override { uint256 wantBal = IERC20Upgradeable(want).balanceOf(address(this)); if (wantBal < _amount) { IMasterChef(MASTER_CHEF).withdraw(poolId, _amount - wantBal, address(this)); } IERC20Upgradeable(want).safeTransfer(vault, _amount); }
16,921,443
./partial_match/1/0x3FBe0374F2c4904c801c40c0D2Ed7f624018321D/sources/RAREPassGiveaway.sol
function to get random index from random word supplied from VRF modulo bias is insignificant for entries less than 100 billion
function _getRandomIndex(uint256 randomWord, uint256 maxIndex) internal pure returns(uint256) { return randomWord % maxIndex; }
9,333,967