file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./full_match/1/0x31a91336414d3B955E494E7d485a6B06b55FC8fB/sources/contracts/vault/VaultAdmin.sol
_recipient can either be a strategy or the Vault/ Withdraw from Strategy to the recipient
function _withdrawFromStrategy( address _recipient, address _strategyFromAddress, address[] calldata _assets, uint256[] calldata _amounts ) internal { require( strategies[_strategyFromAddress].isSupported, "Invalid from Strategy" ); require(_assets.length == _amounts.length, "Parameter length mismatch"); uint256 assetCount = _assets.length; for (uint256 i = 0; i < assetCount; ++i) { IStrategy(_strategyFromAddress).withdraw( _recipient, _assets[i], _amounts[i] ); } }
4,932,147
./partial_match/1/0x0092CD4044E1672c9c513867eb75e6213AF9742f/sources/src/LlamaPolicy.sol
Returns the expiration timestamp of the `role` held by `policyholder`. policyholder Policyholder to get the expiration timestamp of their role. role ID of the role. return The expiration timestamp of the `role` held by `policyholder`.
function roleExpiration(address policyholder, uint8 role) external view returns (uint64) { (,, uint64 expiration,) = roleBalanceCkpts[_tokenId(policyholder)][role].latestCheckpoint(); return expiration; }
9,329,982
/** *Submitted for verification at Etherscan.io on 2022-04-02 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @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 Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev 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 internal _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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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 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}. * * This ERC721 Has been adjusted from OpenZepplins to have a totalSupply method. It also is set up to better handle * batch transactions. Namely it does not update _balances on a call to {_mint} and expects the minting method to do so. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct AddressData { uint128 balance; uint128 numberMinted; } // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted // Only used when `_isSequential` is false uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Tracking the next sequential mint uint256 internal _nextSequential; // This ensures that ownerOf() can still run in constant time // With a max runtime of checking 10 variables, but saves on batch mints tremendously. uint256 internal constant MAX_OWNER_SEQUENCE = 10; // Tracking if the collection is still sequentially minted bool internal _notSequentialMint; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping from token ID to burned // This is necessary because to optimize gas fees for multiple mints a token with // `_owners[tokenId] = address(0)` is not necessarily a token with no owner. mapping(uint256 => bool) internal _burned; // Mapping owner address to token count mapping(address => AddressData) internal _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].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); if (tokenId < _nextSequential) { uint256 lowestTokenToCheck; if (tokenId >= MAX_OWNER_SEQUENCE) { lowestTokenToCheck = tokenId - MAX_OWNER_SEQUENCE + 1; } for (uint256 i = tokenId; i >= lowestTokenToCheck; i--) { if (_owners[i] != address(0)) { return _owners[i]; } } } return _owners[tokenId]; } /** * @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 Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return totalMinted() - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { if (_notSequentialMint) { return _totalMinted; } return _nextSequential; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: 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, owner); } /** * @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 { address owner = ERC721.ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId, owner); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * This was modified to not call _safeTransfer because that would require fetching * ownerOf() twice which is more expensive than doing it together. * _safeTransfer was not modified to take in owner because functions using that * method should be able to assume that it will check for the tokenOwner. * * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { address owner = ERC721.ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId, owner); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @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, ERC721.ownerOf(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) { if (_burned[tokenId]) { return false; } if (tokenId < _nextSequential) { return true; } return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address spender, uint256 tokenId, address owner ) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * 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. * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on transactions */ 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 * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(_notSequentialMint, "_notSequentialMint must be true"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. * * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); uint256 lastNum = _nextSequential + quantity; // ensures ownerOf runs quickly even if user is minting a large number like 100 for ( uint256 i = _nextSequential; i < lastNum; i += MAX_OWNER_SEQUENCE ) { _owners[i] = to; } // Gas is cheaper to have two separate for loops for (uint256 i = _nextSequential; i < lastNum; i++) { emit Transfer(address(0), to, i); require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; } /** * @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); require(owner == _msgSender(), "Cannot burn a token you do not own"); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId, owner); _balances[owner].balance -= 1; _totalBurned += 1; _burned[tokenId] = true; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * WARNING this method assumes the passed in owner is the token owner. This is done because with the gas optimization * calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) * * 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, address owner ) internal virtual { require(owner == 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, from); _balances[from].balance -= 1; _balances[to].balance += 1; _owners[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (nextTokenId < _nextSequential) { if (_owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal virtual { if (_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 {} } /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable( address primaryPayout, address[] memory royalties, uint256[] memory bps ) external payable; } /** * @dev Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set an alternate signer which they can change at any time. This alternate signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. */ abstract contract ERC721Marketplace is ERC721, Ownable { using ECDSA for bytes32; using Strings for uint256; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0x68f5C1e24677Ac4ae845Dde07504EAaD98f82572; uint256 public constant TIME_PER_DECREMENT = 300; uint256 public constant MAX_ROYALTIES_BPS = 9500; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Let's the owner enable another address to lazy mint */ address public alternateSignerAddress; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public ownerRoyaltyBPS; /* Optional addresses to distribute revenue of primary sales of this collection */ address[] public revenueShare; /* Optional basis points for revenue share for primary sales of this collection */ uint256[] public revenueShareBPS; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted( uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash ); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event AltSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event RevenueShareUpdated( address address1, address address2, uint256 bps1, uint256 bps2 ); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (_salePrice * ownerRoyaltyBPS) / 10000; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { require(withdrawAmount <= address(this).balance); IEaselyPayout payoutContract = IEaselyPayout(PAYOUT_CONTRACT_ADDRESS); payoutContract.splitPayable{value: withdrawAmount}( owner(), revenueShare, revenueShareBPS ); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the alternate signer is */ function setAltSigner(address alt) external onlyOwner { alternateSignerAddress = alt; emit AltSignerChanged(alt); } /** * @dev see {_setRoyalties} */ function setRevenueShare( address[2] memory newAddresses, uint256[2] memory newBPS ) external onlyOwner { _setRevenueShare(newAddresses, newBPS); emit RevenueShareUpdated( newAddresses[0], newAddresses[1], newBPS[0], newBPS[1] ); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner { _setRoyaltiesBPS(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev returns how many tokens the given address has minted. */ function mintCount(address addr) external view returns (uint256) { return _balances[addr].numberMinted; } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require( _msgSender() == ERC721.ownerOf(tokenId), "Not the owner of the token" ); return _hashForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require( _addressToActiveVersion[seller] == version, "Incorrect signature version" ); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashSold( seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature ); _safeTransfer(seller, _msgSender(), tokenId, ""); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @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 override returns (string memory) { return "ipfs://"; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = ownerRoyaltyBPS; return ownerBPS; } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require( startingTimestamp < endingTimestamp, "Must end after it starts" ); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - (diff / totalDecrements) * decrements; } /** * @dev Sets secondary BPS amount */ function _setRoyaltiesBPS(uint256 newBPS) internal { require( ownerRoyaltyBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); ownerRoyaltyBPS = newBPS; } /** * @dev Sets primary revenue share */ function _setRevenueShare( address[2] memory newAddresses, uint256[2] memory newBPS ) internal { require( newBPS[0] + newBPS[1] <= MAX_ROYALTIES_BPS, "Revenue share too high" ); revenueShare = newAddresses; revenueShareBPS = newBPS; } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require( signer == owner() || signer == alternateSignerAddress, "Not valid signer." ); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashSold( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == seller, "Not signed by current seller" ); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, seller, _msgSender(), hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForSale( owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps ) ); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721Marketplace. * It requires that the creator knows the total number of NFTs they want and has an IPFS * hash that is a directory with all the tokenIds from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint, one allows the owner or alternate signer to approve single use signatures * for specific wallet addresses and the other allows a general mint signature that anyone can use. * * Minting from this collection is always random, this can be done either with a reveal * mechanism that has a random offset, or on-chain randomness if the collection is already revealed. */ contract ERC721RandomizedCollectionV2 is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; bool private hasInit = false; uint256 public constant MAX_SUPPLY_LIMIT = 10**9; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; // Used to shuffle tokenURI upon reveal uint256 public offset; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string private ipfsHash; // Randomized Collection Events event Minted( address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash ); event IpfsRevealed(string ipfsHash, bool locked); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) ERC721(strings[0], strings[1]) { addresses[0] = _msgSender(); _init(bools, addresses, uints, strings); } function init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) external { _init(bools, addresses, uints, strings); } function _init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _notSequentialMint = bools[1]; _owner = msg.sender; address[2] memory revenueShare = [addresses[0], addresses[1]]; alternateSignerAddress = addresses[2]; _setRoyaltiesBPS(uints[0]); _setRevenueShare(revenueShare, [uints[1], uints[2]]); maxSupply = uints[3]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 100 mints a transaction so users cannot exceed gas limit if (uints[4] == 0 || uints[4] >= 25000) { transactionMax = 25000; } else { transactionMax = uints[4]; } maxMint = uints[5]; _name = strings[0]; _symbol = strings[1]; ipfsHash = strings[2]; if (_notSequentialMint) { emit IpfsRevealed(ipfsHash, false); } } function isRevealed() external view returns (bool) { return _notSequentialMint; } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a creator can decide if they want to * lock the unminted tokens or enable them for on-chain randomness minting. * * IMPORTANT - this function can only be called ONCE, if a wrong IPFS hash * is submitted by the owner, it cannot ever be switched to a different one. */ function lockTokenURI(string calldata revealIPFSHash, bool lockOnReveal) external onlyOwner { require(!_notSequentialMint, "The token URI has already been set"); offset = _random(maxSupply); ipfsHash = revealIPFSHash; _notSequentialMint = true; if (lockOnReveal) { // This will lock the unminted tokens at reveal time maxSupply = _nextSequential; } _totalMinted = _nextSequential; emit IpfsRevealed(revealIPFSHash, lockOnReveal); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_notSequentialMint) { return string(abi.encodePacked(_baseURI(), ipfsHash)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string( abi.encodePacked(_baseURI(), ipfsHash, "/", offsetId.toString()) ); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require( version == _addressToActiveVersion[owner()], "This presale version is disabled" ); require(allowedAddress == _msgSender(), "Invalid sender"); uint256 totalPrice = price * buyAmount; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, totalPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForAllowList(allowedAddress, nonce, version, price, amount) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForMint(version, amount, pricesAndTimestamps) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), amount, pricesAndTimestamps, version ) ); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require( maxMint == 0 || _balances[buyer].numberMinted + amount <= maxMint, "Buyer over mint maximum" ); if (_notSequentialMint) { _mintRandomIndex(buyer, amount); _totalMinted += amount; } else { _safeMintSequential(buyer, amount); } } }
Allows anyone to buy an amount of tokens at a price which matches the signature that the owner or alternate signer has approved/
function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, totalPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); }
15,379,584
pragma solidity ^0.4.13; import "./owned.sol"; import "./FixedSupplyToken.sol"; contract Exchange is owned { /////////////////////// // GENERAL STRUCTURE // /////////////////////// struct Offer { uint amount; address who; } struct OrderBook { uint higherPrice; uint lowerPrice; mapping (uint => Offer) offers; uint offers_key; uint offers_length; } struct Token { address tokenContract; string symbolName; mapping (uint => OrderBook) buyBook; uint curBuyPrice; uint lowestBuyPrice; uint amountBuyPrices; mapping (uint => OrderBook) sellBook; uint curSellPrice; uint highestSellPrice; uint amountSellPrices; } //we support a max of 255 tokens... mapping (uint8 => Token) tokens; uint8 symbolNameIndex; ////////////// // BALANCES // ////////////// mapping (address => mapping (uint8 => uint)) tokenBalanceForAddress; mapping (address => uint) balanceEthForAddress; //////////// // EVENTS // //////////// //EVENTS for Deposit/withdrawal event DepositForTokenReceived(address indexed _from, uint indexed _symbolIndex, uint _amount, uint _timestamp); event WithdrawalToken(address indexed _to, uint indexed _symbolIndex, uint _amount, uint _timestamp); event DepositForEthReceived(address indexed _from, uint _amount, uint _timestamp); event WithdrawalEth(address indexed _to, uint _amount, uint _timestamp); //events for orders event LimitSellOrderCreated(uint indexed _symbolIndex, address indexed _who, uint _amountTokens, uint _priceInWei, uint _orderKey); event SellOrderFulfilled(uint indexed _symbolIndex, uint _amount, uint _priceInWei, uint _orderKey); event SellOrderCanceled(uint indexed _symbolIndex, uint _priceInWei, uint _orderKey); event LimitBuyOrderCreated(uint indexed _symbolIndex, address indexed _who, uint _amountTokens, uint _priceInWei, uint _orderKey); event BuyOrderFulfilled(uint indexed _symbolIndex, uint _amount, uint _priceInWei, uint _orderKey); event BuyOrderCanceled(uint indexed _symbolIndex, uint _priceInWei, uint _orderKey); //events for management event TokenAddedToSystem(uint _symbolIndex, string _token, uint _timestamp); ////////////////////////////////// // DEPOSIT AND WITHDRAWAL ETHER // ////////////////////////////////// function depositEther() payable { require(balanceEthForAddress[msg.sender] + msg.value >= balanceEthForAddress[msg.sender]); balanceEthForAddress[msg.sender] += msg.value; DepositForEthReceived(msg.sender, msg.value, now); } function withdrawEther(uint amountInWei) { require(balanceEthForAddress[msg.sender] - amountInWei >= 0); require(balanceEthForAddress[msg.sender] - amountInWei <= balanceEthForAddress[msg.sender]); balanceEthForAddress[msg.sender] -= amountInWei; msg.sender.transfer(amountInWei); WithdrawalEth(msg.sender, amountInWei, now); } function getEthBalanceInWei() constant returns (uint){ return balanceEthForAddress[msg.sender]; } ////////////////////// // TOKEN MANAGEMENT // ////////////////////// function addToken(string symbolName, address erc20TokenAddress) onlyowner { require(!hasToken(symbolName)); require(symbolNameIndex + 1 > symbolNameIndex); symbolNameIndex++; tokens[symbolNameIndex].symbolName = symbolName; tokens[symbolNameIndex].tokenContract = erc20TokenAddress; TokenAddedToSystem(symbolNameIndex, symbolName, now); } function hasToken(string symbolName) constant returns (bool) { uint8 index = getSymbolIndex(symbolName); if (index == 0) { return false; } return true; } function getSymbolIndex(string symbolName) internal returns (uint8) { for (uint8 i = 1; i <= symbolNameIndex; i++) { if (stringsEqual(tokens[i].symbolName, symbolName)) { return i; } } return 0; } function getSymbolIndexOrThrow(string symbolName) returns (uint8) { uint8 index = getSymbolIndex(symbolName); require(index > 0); return index; } ////////////////////////////////// // DEPOSIT AND WITHDRAWAL TOKEN // ////////////////////////////////// function depositToken(string symbolName, uint amount) { uint8 symbolNameIndex = getSymbolIndexOrThrow(symbolName); require(tokens[symbolNameIndex].tokenContract != address(0)); ERC20Interface token = ERC20Interface(tokens[symbolNameIndex].tokenContract); require(token.transferFrom(msg.sender, address(this), amount) == true); require(tokenBalanceForAddress[msg.sender][symbolNameIndex] + amount >= tokenBalanceForAddress[msg.sender][symbolNameIndex]); tokenBalanceForAddress[msg.sender][symbolNameIndex] += amount; DepositForTokenReceived(msg.sender, symbolNameIndex, amount, now); } function withdrawToken(string symbolName, uint amount) { uint8 symbolNameIndex = getSymbolIndexOrThrow(symbolName); require(tokens[symbolNameIndex].tokenContract != address(0)); ERC20Interface token = ERC20Interface(tokens[symbolNameIndex].tokenContract); require(tokenBalanceForAddress[msg.sender][symbolNameIndex] - amount >= 0); require(tokenBalanceForAddress[msg.sender][symbolNameIndex] - amount <= tokenBalanceForAddress[msg.sender][symbolNameIndex]); tokenBalanceForAddress[msg.sender][symbolNameIndex] -= amount; require(token.transfer(msg.sender, amount) == true); WithdrawalToken(msg.sender, symbolNameIndex, amount, now); } function getBalance(string symbolName) constant returns (uint) { uint8 symbolNameIndex = getSymbolIndexOrThrow(symbolName); return tokenBalanceForAddress[msg.sender][symbolNameIndex]; } ///////////////////////////// // ORDER BOOK - BID ORDERS // ///////////////////////////// function getBuyOrderBook(string symbolName) constant returns (uint[], uint[]) { } ///////////////////////////// // ORDER BOOK - ASK ORDERS // ///////////////////////////// function getSellOrderBook(string symbolName) constant returns (uint[], uint[]) { } //////////////////////////// // NEW ORDER - BID ORDER // /////////////////////////// function buyToken(string symbolName, uint priceInWei, uint amount) { } //////////////////////////// // NEW ORDER - ASK ORDER // /////////////////////////// function sellToken(string symbolName, uint priceInWei, uint amount) { } ////////////////////////////// // CANCEL LIMIT ORDER LOGIC // ////////////////////////////// function cancelOrder(string symbolName, bool isSellOrder, uint priceInWei, uint offerKey) { } //////////////////////////////// // STRING COMPARISON FUNCTION // //////////////////////////////// function stringsEqual(string storage _a, string memory _b) internal returns (bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) { return false; } // @todo unroll this loop for (uint i = 0; i < a.length; i ++) { if (a[i] != b[i]) { return false; } } return true; } }
// ORDER BOOK - BID ORDERS //
function getBuyOrderBook(string symbolName) constant returns (uint[], uint[]) { }
941,843
// SPDX-License-Identifier: MIT /** * @title A LIT Invitation To Kindness * @author Transient Labs, Copyright (C) 2022 * @notice ERC 1155 contract, single owner, merkle claim * @dev includes the public parameter `name` so it works with OS */ /* ( ( ( ) ( )\ ) )\ ) * ) )\ ) ) ) * ) ( /( ( )\ (()/( (()/( ` ) /( (()/( ) ( ( /( ) ( /( ( ` ) /( )\()) ( )\ ) ( ((((_)( /(_)) /(_)) ( )(_)) /(_)) ( /(( )\ )\()) ( /( )\()) )\ ( ( ( )(_)) ( |((_)\ )\ ( (()/( ( ))\ ( ( )\ _ )\ (_)) (_)) (_(_()) (_)) )\ ) (_))\ ((_) (_))/ )(_)) (_))/ ((_) )\ )\ ) (_(_()) )\ |_ ((_) ((_) )\ ) ((_)) )\ ) /((_) )\ )\ (_)_\(_) | | |_ _| |_ _| |_ _| _(_/( _)((_) (_) | |_ ((_)_ | |_ (_) ((_) _(_/( |_ _| ((_) | |/ / (_) _(_/( _| | _(_/( (_)) ((_) ((_) / _ \ | |__ | | | | | | | ' \)) \ V / | | | _| / _` | | _| | | / _ \ | ' \)) | | / _ \ ' < | | | ' \)) / _` | | ' \)) / -_) (_-< (_-< /_/ \_\ |____| |___| |_| |___| |_||_| \_/ |_| \__| \__,_| \__| |_| \___/ |_||_| |_| \___/ _|\_\ |_| |_||_| \__,_| |_||_| \___| /__/ /__/ ___ __ ___ ______ _ __ __ __ / _ \___ _ _____ _______ ___/ / / _ )__ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___ / ___/ _ \ |/|/ / -_) __/ -_) _ / / _ / // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-< /_/ \___/__,__/\__/_/ \__/\_,_/ /____/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/ /___/ */ pragma solidity ^0.8.0; import "ERC1155.sol"; import "Ownable.sol"; import "Strings.sol"; import "MerkleProof.sol"; import "EIP2981.sol"; contract InvitationToKindness is ERC1155, EIP2981, Ownable { using Strings for uint256; bytes32 private litRiderMerkleRoot; bytes32 private rareRiderMerkleRoot; uint256 constant LIT_RIDER = 0; uint256 constant LIT_PAMP = 1; uint256 constant LIT_CDM = 2; mapping(address => bool) private hasMinted; bool public claimOpen; uint256[] private availableRareRiderIds; uint256[] private rareRiderSupply; string public name = "A LIT Invitation to Kindness"; constructor(bytes32 _litRiderMerkleRoot, bytes32 _rareRiderMerkleRoot, address _royaltyRecipient, uint256 _royaltyAmount) EIP2981(_royaltyRecipient, _royaltyAmount) ERC1155("") Ownable() { availableRareRiderIds = [LIT_PAMP, LIT_CDM]; rareRiderSupply = [334, 30]; litRiderMerkleRoot = _litRiderMerkleRoot; rareRiderMerkleRoot = _rareRiderMerkleRoot; } /** * @notice overrides supportsInterface function * @param _interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165 * @return a boolean saying if this contract supports the interface or not */ function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC1155, EIP2981) returns (bool) { return super.supportsInterface(_interfaceId); } /** * @notice function to update allowlist merkle root if needed * @dev requires owner * @param _litRiderRoot is the new lit rider merkle root * @param _rareRiderRoot is the new rare rider merkle root*/ function updateAllowlistRoots(bytes32 _litRiderRoot, bytes32 _rareRiderRoot) public onlyOwner { litRiderMerkleRoot = _litRiderRoot; rareRiderMerkleRoot = _rareRiderRoot; } /** * @notice sets the baseURI for the tokens * @dev requires owner * @param _uri is the base URI set for each token */ function setBaseURI(string memory _uri) public onlyOwner { _setURI(_uri); } /** * @notice function to change the royalty recipient * @dev requires owner * @dev this is useful if an account gets compromised or anything like that * @param _newRecipient is the new royalty recipient */ function changeRoyaltyRecipient(address _newRecipient) public onlyOwner { require(_newRecipient != address(0), "Error: new recipient is the zero address"); royaltyAddr = _newRecipient; } /** * @notice function to change the royalty percentage * @dev requires owner * @dev this is useful if the amount was set improperly at contract creation. This can in fact happen... humans are prone to mistakes :) * @param _newPerc is the new royalty percentage, in basis points (out of 10,000) */ function changeRoyaltyPercentage(uint256 _newPerc) public onlyOwner { require(_newPerc <= 10000, "Error: new percentage is greater than 10,0000"); royaltyPerc = _newPerc; } /** * @notice getter function for if an address has minted * @param _address is the address to check * @return boolean */ function getHasMinted(address _address) public returns (bool){ return hasMinted[_address]; } /** * @notice function to return uri for a specific token type * @param _tokenId is the uint256 representation of a token ID * @return string representing the uri for the token id */ function uri(uint256 _tokenId) public view virtual override returns (string memory) { require(_tokenId == LIT_RIDER || _tokenId == LIT_CDM || _tokenId == LIT_PAMP, "Error: non-existent token id"); return string(abi.encodePacked(ERC1155.uri(_tokenId), _tokenId.toString())); } /** * @notice function to set the claim status * @dev requires owner * @param _status is the status to set the claim to */ function setClaimStatus(bool _status) public onlyOwner { claimOpen = _status; } /** * @notice function for minting riders * @dev requires owner * @param _litRiderMerkleProof is the proof for lit riders * @param _rareRiderMerkleProof is the proof for rare riders */ function mint(bytes32[] calldata _litRiderMerkleProof, bytes32[] calldata _rareRiderMerkleProof) public { require(claimOpen, "Error: claim not open"); require(!hasMinted[msg.sender], "Error: already claimed"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); bool isLitRider = MerkleProof.verify(_litRiderMerkleProof, litRiderMerkleRoot, leaf); require(isLitRider, "Error: not on the allowlist for the claim"); bool isRareRider = MerkleProof.verify(_rareRiderMerkleProof, rareRiderMerkleRoot, leaf); if (isRareRider && availableRareRiderIds.length != 0) { _mint(msg.sender, LIT_RIDER, 1, ""); uint256 rider = _getRandomNum(availableRareRiderIds.length); _mint(msg.sender, availableRareRiderIds[rider], 1, ""); rareRiderSupply[rider]--; if (rareRiderSupply[rider] == 0) { availableRareRiderIds[rider] = availableRareRiderIds[availableRareRiderIds.length - 1]; availableRareRiderIds.pop(); rareRiderSupply[rider] = rareRiderSupply[rareRiderSupply.length - 1]; rareRiderSupply.pop(); } } else { _mint(msg.sender, LIT_RIDER, 2, ""); } hasMinted[msg.sender] = true; } /** * @notice function for minting specific rider to address * @dev only owner * @dev only used as backup * @param _tokenId is the token id to mint * @param _address is the address to mint to */ function adminMint(address _address, uint256 _tokenId) public onlyOwner { require(_tokenId == LIT_RIDER || _tokenId == LIT_CDM || _tokenId == LIT_PAMP, "Error: invalid token id"); _mint(_address, _tokenId, 1, ""); } /** * @dev Generates a pseudo-random number * @param _upper is a uint256 meant to be the upper bound of the random number generation */ function _getRandomNum(uint256 _upper) private view returns (uint256) { uint256 random = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender))); return random % _upper; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "IERC1155.sol"; import "IERC1155Receiver.sol"; import "IERC1155MetadataURI.sol"; import "Address.sol"; import "Context.sol"; import "ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // 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 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (access/Ownable.sol) pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT /** * @title EIP 2981 base contract * @author Transient Labs, Copyright (C) 2021 * @notice contract implementation of EIP 2981 */ /* ####### # # ##### ## # # #### # ###### # # ##### # ## ##### #### # # # # # ## # # # # ## # # # # # # # # # # # # # # # # #### # ##### # # # # # # # ##### #### # ##### ###### # # # # # # # # # # # ###### # # # # # # # # # ## # # # # # ## # # # # # # # # # # # # # # # #### # ###### # # # ####### # # ##### #### 0101010011100101100000110111011100101101000110010011011101110100 01001100110000011000101110011 */ pragma solidity ^0.8.0; import "ERC165.sol"; import "IEIP2981.sol"; contract EIP2981 is IEIP2981, ERC165 { address internal royaltyAddr; uint256 internal royaltyPerc; // percentage in basis (out of 10,000) /** * @notice constructor * @dev need inheriting contracts to accept the parameters in their constructor * @param addr is the royalty payout address * @param perc is the royalty percentage, multiplied by 10000. Ex: 7.5% => 750 */ constructor(address addr, uint256 perc) { royaltyAddr = addr; royaltyPerc = perc; } /** * @notice override ERC 165 implementation of this function * @dev if using this contract with another contract that suppports ERC 265, will have to override in the inheriting contract */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId); } /** * @notice EIP 2981 royalty support * @dev royalty payout made to the owner of the contract and the owner can't be the 0 address * @dev royalty amount determined when contract is deployed, and then divided by 10000 in this function * @dev royalty amount not dependent on _tokenId */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { require(royaltyAddr != address(0)); return (royaltyAddr, royaltyPerc * _salePrice / 10000); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// /// @dev Interface for the NFT Royalty Standard /// interface IEIP2981 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver,uint256 royaltyAmount); }
function to update allowlist merkle root if needed requires owner _litRiderRoot is the new lit rider merkle root _rareRiderRoot is the new rare rider merkle root/
function updateAllowlistRoots(bytes32 _litRiderRoot, bytes32 _rareRiderRoot) public onlyOwner { litRiderMerkleRoot = _litRiderRoot; rareRiderMerkleRoot = _rareRiderRoot; }
1,204,634
pragma solidity ^0.4.24; interface MilAuthInterface { function requiredSignatures() external view returns(uint256); function requiredDevSignatures() external view returns(uint256); function adminCount() external view returns(uint256); function devCount() external view returns(uint256); function adminName(address _who) external view returns(bytes32); function isAdmin(address _who) external view returns(bool); function isDev(address _who) external view returns(bool); function checkGameRegiester(address _gameAddr) external view returns(bool); function checkGameClosed(address _gameAddr) external view returns(bool); } interface MillionaireInterface { function invest(address _addr, uint256 _affID, uint256 _mfCoin, uint256 _general) external payable; function updateGenVaultAndMask(address _addr, uint256 _affID) external payable; function clearGenVaultAndMask(address _addr, uint256 _affID, uint256 _eth, uint256 _milFee) external; function assign(address _addr) external payable; function splitPot() external payable; } interface MilFoldInterface { function addPot() external payable; function activate() external; } contract Milevents { // fired whenever a player registers event onNewPlayer ( address indexed playerAddress, uint256 playerID, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 rid, //current round id address indexed buyerAddress, //buyer address uint256 compressData, //action << 96 | time << 64 | drawCode << 32 | txAction << 8 | roundState uint256 eth, //buy amount uint256 totalPot, //current total pot uint256 tickets, //buy tickets uint256 timeStamp //buy time ); // fired at end of buy or reload event onGameClose ( address indexed gameAddr, //game address uint256 amount, //split eth amount uint256 timeStamp //close time ); // fired at time who satisfy the reward condition event onReward ( address indexed rewardAddr, //reward address Mildatasets.RewardType rewardType, //rewardType uint256 amount //reward amount ); // fired whenever theres a withdraw event onWithdraw ( address indexed playerAddress, uint256 ethOut, uint256 timeStamp ); event onAffiliatePayout ( address indexed affiliateAddress, address indexed buyerAddress, uint256 eth, uint256 timeStamp ); // fired at every ico event onICO ( address indexed buyerAddress, //user address who buy ico uint256 buyAmount, //buy ico amount uint256 buyMf, //eth exchange mfcoin amount uint256 totalIco, //now total ico amount bool ended //is ico ended ); // fired whenever an player win the playround event onPlayerWin( address indexed addr, uint256 roundID, uint256 winAmount, uint256 winNums ); event onClaimWinner( address indexed addr, uint256 winnerNum, uint256 totalNum ); event onBuyMFCoins( address indexed addr, uint256 ethAmount, uint256 mfAmount, uint256 timeStamp ); event onSellMFCoins( address indexed addr, uint256 ethAmount, uint256 mfAmount, uint256 timeStamp ); event onUpdateGenVault( address indexed addr, uint256 mfAmount, uint256 genAmount, uint256 ethAmount ); } contract Millionaire is MillionaireInterface,Milevents { using SafeMath for *; using MFCoinsCalc for uint256; //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant private name_ = "Millionaire Official"; uint256 constant private icoRndMax_ = 2 weeks; // ico max period uint256 private icoEndtime_; // ico end time uint256 private icoAmount_; // ico eth amount; uint256 private sequence_; // affiliate id sequence bool private activated_; // mark contract is activated; bool private icoEnd_; // is ico ended; MilFoldInterface public milFold_; // milFold contract MilAuthInterface constant private milAuth_ = MilAuthInterface(0xf856f6a413f7756FfaF423aa2101b37E2B3aFFD9); uint256 public globalMask_; // use to calc player gen uint256 public mfCoinPool_; // MFCoin Pool uint256 public totalSupply_; // MFCoin current supply address constant private fundAddr_ = 0xB0c7Dc00E8A74c9dEc8688EFb98CcB2e24584E3B; // foundation address uint256 constant private REGISTER_FEE = 0.01 ether; // register affiliate fees uint256 constant private MAX_ICO_AMOUNT = 3000 ether; // max tickets you can buy one time mapping(address => uint256) private balance_; // player coin balance mapping(uint256 => address) private plyrAddr_; // (id => address) returns player id by address mapping(address => Mildatasets.Player) private plyr_; // (addr => data) player data //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready start"); _; } /** * @dev prevents contracts from interacting with Millionare */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 0.1 ether, "must > 0.1 ether"); _; } /** * @dev check sender must be devs */ modifier onlyDevs() { require(milAuth_.isDev(msg.sender) == true, "msg sender is not a dev"); _; } /** * @dev default buy set to ico */ function() public isActivated() isHuman() isWithinLimits(msg.value) payable { icoCore(msg.value); } /** * @dev buy MFCoin use eth in ico phase */ function buyICO() public isActivated() isHuman() isWithinLimits(msg.value) payable { icoCore(msg.value); } function icoCore(uint256 _eth) private { if (icoEnd_) { plyr_[msg.sender].eth = plyr_[msg.sender].eth.add(_eth); } else { if (block.timestamp > icoEndtime_ || icoAmount_ >= MAX_ICO_AMOUNT) { plyr_[msg.sender].eth = plyr_[msg.sender].eth.add(_eth); icoEnd_ = true; milFold_.activate(); emit onICO(msg.sender, 0, 0, MAX_ICO_AMOUNT, icoEnd_); } else { uint256 ethAmount = _eth; if (ethAmount + icoAmount_ > MAX_ICO_AMOUNT) { ethAmount = MAX_ICO_AMOUNT.sub(icoAmount_); plyr_[msg.sender].eth = _eth.sub(ethAmount); } icoAmount_ = icoAmount_.add(ethAmount); uint256 converts = ethAmount.mul(65)/100; uint256 pot = ethAmount.sub(converts); //65% of your eth use to convert MFCoin uint256 buytMf = buyMFCoins(msg.sender, converts); //35% of your eth use to pot milFold_.addPot.value(pot)(); if (icoAmount_ >= MAX_ICO_AMOUNT) { icoEnd_ = true; milFold_.activate(); } emit onICO(msg.sender, ethAmount, buytMf, icoAmount_, icoEnd_); } } } /** * @dev withdraw all you earnings to your address */ function withdraw() public isActivated() isHuman() { updateGenVault(msg.sender); if (plyr_[msg.sender].eth > 0) { uint256 amount = plyr_[msg.sender].eth; plyr_[msg.sender].eth = 0; msg.sender.transfer(amount); emit onWithdraw( msg.sender, amount, block.timestamp ); } } /** * @dev register as a affiliate */ function registerAff() public isHuman() payable { require (msg.value >= REGISTER_FEE, "register affiliate fees must >= 0.01 ether"); require (plyr_[msg.sender].playerID == 0, "you already register!"); plyrAddr_[++sequence_] = msg.sender; plyr_[msg.sender].playerID = sequence_; fundAddr_.transfer(msg.value); emit onNewPlayer(msg.sender,sequence_, block.timestamp); } function setMilFold(address _milFoldAddr) public onlyDevs { require(address(milFold_) == 0, "milFold has been set"); require(_milFoldAddr != 0, "milFold is invalid"); milFold_ = MilFoldInterface(_milFoldAddr); } function activate() public onlyDevs { require(address(milFold_) != 0, "milFold has not been set"); require(activated_ == false, "ICO already activated"); // activate the ico activated_ = true; icoEndtime_ = block.timestamp + icoRndMax_; } /** * @dev external contracts interact with Millionare via investing MF Coin * @param _addr player's address * @param _affID affiliate ID * @param _mfCoin eth amount to buy MF Coin * @param _general eth amount assign to general */ function invest(address _addr, uint256 _affID, uint256 _mfCoin, uint256 _general) external isActivated() payable { require(milAuth_.checkGameRegiester(msg.sender), "game no register"); require(_mfCoin.add(_general) <= msg.value, "account is insufficient"); if (msg.value > 0) { uint256 tmpAffID = 0; if (_affID == 0 || plyrAddr_[_affID] == _addr) { tmpAffID = plyr_[_addr].laff; } else if (plyr_[_addr].laff == 0 && plyrAddr_[_affID] != address(0)) { plyr_[_addr].laff = _affID; tmpAffID = _affID; } // if affiliate not exist, assign affiliate to general, i.e. set affiliate to zero uint256 _affiliate = msg.value.sub(_mfCoin).sub(_general); if (tmpAffID > 0 && _affiliate > 0) { address affAddr = plyrAddr_[tmpAffID]; plyr_[affAddr].affTotal = plyr_[affAddr].affTotal.add(_affiliate); plyr_[affAddr].eth = plyr_[affAddr].eth.add(_affiliate); emit onAffiliatePayout(affAddr, _addr, _affiliate, block.timestamp); } if (totalSupply_ > 0) { uint256 delta = _general.mul(1 ether).div(totalSupply_); globalMask_ = globalMask_.add(delta); } else { //if nobody hold MFCoin,so nobody get general,it will give foundation fundAddr_.transfer(_general); } updateGenVault(_addr); buyMFCoins(_addr, _mfCoin); emit onUpdateGenVault(_addr, balance_[_addr], plyr_[_addr].genTotal, plyr_[_addr].eth); } } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(address _addr) private view returns(uint256) { uint256 diffMask = globalMask_.sub(plyr_[_addr].mask); if (diffMask > 0) { return diffMask.mul(balance_[_addr]).div(1 ether); } } /** * @dev updates masks for round and player when keys are bought */ function updateGenVaultAndMask(address _addr, uint256 _affID) external payable { require(msg.sender == address(milFold_), "no authrity"); if (msg.value > 0) { /** * 50/80 use to convert MFCoin * 10/80 use to affiliate * 20/80 use to general */ uint256 converts = msg.value.mul(50).div(80); uint256 tmpAffID = 0; if (_affID == 0 || plyrAddr_[_affID] == _addr) { tmpAffID = plyr_[_addr].laff; } else if (plyr_[_addr].laff == 0 && plyrAddr_[_affID] != address(0)) { plyr_[_addr].laff = _affID; tmpAffID = _affID; } uint256 affAmount = 0; if (tmpAffID > 0) { affAmount = msg.value.mul(10).div(80); address affAddr = plyrAddr_[tmpAffID]; plyr_[affAddr].affTotal = plyr_[affAddr].affTotal.add(affAmount); plyr_[affAddr].eth = plyr_[affAddr].eth.add(affAmount); emit onAffiliatePayout(affAddr, _addr, affAmount, block.timestamp); } if (totalSupply_ > 0) { uint256 delta = msg.value.sub(converts).sub(affAmount).mul(1 ether).div(totalSupply_); globalMask_ = globalMask_.add(delta); } else { //if nobody hold MFCoin,so nobody get general,it will give foundation fundAddr_.transfer(msg.value.sub(converts).sub(affAmount)); } updateGenVault(_addr); buyMFCoins(_addr, converts); emit onUpdateGenVault(_addr, balance_[_addr], plyr_[_addr].genTotal, plyr_[_addr].eth); } } /** * @dev game contract has been paid 20% amount for Millionaire and paid back now */ function clearGenVaultAndMask(address _addr, uint256 _affID, uint256 _eth, uint256 _milFee) external { require(msg.sender == address(milFold_), "no authrity"); //check player eth balance is enough pay for uint256 _earnings = calcUnMaskedEarnings(_addr); require(plyr_[_addr].eth.add(_earnings) >= _eth, "eth balance not enough"); /** * 50/80 use to convert MFCoin * 10/80 use to affiliate * 20/80 use to general */ uint256 converts = _milFee.mul(50).div(80); uint256 tmpAffID = 0; if (_affID == 0 || plyrAddr_[_affID] == _addr) { tmpAffID = plyr_[_addr].laff; } else if (plyr_[_addr].laff == 0 && plyrAddr_[_affID] != address(0)) { plyr_[_addr].laff = _affID; tmpAffID = _affID; } uint256 affAmount = 0; if (tmpAffID > 0) { affAmount = _milFee.mul(10).div(80); address affAddr = plyrAddr_[tmpAffID]; plyr_[affAddr].affTotal = plyr_[affAddr].affTotal.add(affAmount); plyr_[affAddr].eth = plyr_[affAddr].eth.add(affAmount); emit onAffiliatePayout(affAddr, _addr, affAmount, block.timestamp); } if (totalSupply_ > 0) { uint256 delta = _milFee.sub(converts).sub(affAmount).mul(1 ether).div(totalSupply_); globalMask_ = globalMask_.add(delta); } else { //if nobody hold MFCoin,so nobody get general,it will give foundation fundAddr_.transfer(_milFee.sub(converts).sub(affAmount)); } updateGenVault(_addr); buyMFCoins(_addr,converts); plyr_[_addr].eth = plyr_[_addr].eth.sub(_eth); milFold_.addPot.value(_eth.sub(_milFee))(); emit onUpdateGenVault(_addr, balance_[_addr], plyr_[_addr].genTotal, plyr_[_addr].eth); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(address _addr) private { uint256 _earnings = calcUnMaskedEarnings(_addr); if (_earnings > 0) { plyr_[_addr].mask = globalMask_; plyr_[_addr].genTotal = plyr_[_addr].genTotal.add(_earnings); plyr_[_addr].eth = plyr_[_addr].eth.add(_earnings); } else if (globalMask_ > plyr_[_addr].mask) { plyr_[_addr].mask = globalMask_; } } /** * @dev convert eth to coin * @param _addr user address * @return return back coins */ function buyMFCoins(address _addr, uint256 _eth) private returns(uint256) { uint256 _coins = calcCoinsReceived(_eth); mfCoinPool_ = mfCoinPool_.add(_eth); totalSupply_ = totalSupply_.add(_coins); balance_[_addr] = balance_[_addr].add(_coins); emit onBuyMFCoins(_addr, _eth, _coins, now); return _coins; } /** * @dev sell coin to eth * @param _coins sell coins * @return return back eth */ function sellMFCoins(uint256 _coins) public { require(icoEnd_, "ico phase not end"); require(balance_[msg.sender] >= _coins, "coins amount is out of range"); updateGenVault(msg.sender); uint256 _eth = totalSupply_.ethRec(_coins); mfCoinPool_ = mfCoinPool_.sub(_eth); totalSupply_ = totalSupply_.sub(_coins); balance_[msg.sender] = balance_[msg.sender].sub(_coins); if (milAuth_.checkGameClosed(address(milFold_))) { plyr_[msg.sender].eth = plyr_[msg.sender].eth.add(_eth); } else { /** * 10/100 transfer to pot * 90/100 transfer to owner */ uint256 earnAmount = _eth.mul(90).div(100); plyr_[msg.sender].eth = plyr_[msg.sender].eth.add(earnAmount); milFold_.addPot.value(_eth.sub(earnAmount))(); } emit onSellMFCoins(msg.sender, earnAmount, _coins, now); } /** * @dev anyone winner of milfold will call this function * @param _addr winner address */ function assign(address _addr) external payable { require(msg.sender == address(milFold_), "no authrity"); plyr_[_addr].eth = plyr_[_addr].eth.add(msg.value); } /** * @dev If unfortunate the game has problem or has no winner at long time, we'll end the game and divide the pot equally among all MF users */ function splitPot() external payable { require(milAuth_.checkGameClosed(msg.sender), "game has not been closed"); uint256 delta = msg.value.mul(1 ether).div(totalSupply_); globalMask_ = globalMask_.add(delta); emit onGameClose(msg.sender, msg.value, now); } /** * @dev returns ico info * @return ico end time * @return already ico summary * @return ico phase is end */ function getIcoInfo() public view returns(uint256, uint256, bool) { return (icoAmount_, icoEndtime_, icoEnd_); } /** * @dev returns player info based on address * @param _addr address of the player you want to lookup * @return player ID * @return player eth balance * @return player MFCoin * @return general vault * @return affiliate vault */ function getPlayerAccount(address _addr) public isActivated() view returns(uint256, uint256, uint256, uint256, uint256) { uint256 genAmount = calcUnMaskedEarnings(_addr); return ( plyr_[_addr].playerID, plyr_[_addr].eth.add(genAmount), balance_[_addr], plyr_[_addr].genTotal.add(genAmount), plyr_[_addr].affTotal ); } /** * @dev give _eth can convert how much MFCoin * @param _eth eth i will give * @return MFCoin will return back */ function calcCoinsReceived(uint256 _eth) public view returns(uint256) { return mfCoinPool_.keysRec(_eth); } /** * @dev returns current eth price for X coins. * @param _coins number of coins desired (in 18 decimal format) * @return amount of eth needed to send */ function calcEthReceived(uint256 _coins) public view returns(uint256) { if (totalSupply_ < _coins) { return 0; } return totalSupply_.ethRec(_coins); } function getMFBalance(address _addr) public view returns(uint256) { return balance_[_addr]; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library Mildatasets { // between `DRAWN' and `ASSIGNED', someone need to claim winners. enum RoundState { UNKNOWN, // aim to differ from normal states STARTED, // start current round STOPPED, // stop current round DRAWN, // draw code ASSIGNED // assign to foundation, winners, and migrate the rest to the next round } // MilFold Transaction Action. enum TxAction { UNKNOWN, // default BUY, // buy or reload tickets and so on DRAW, // draw code of game ASSIGN, // assign to winners ENDROUND // end game and start new round } // RewardType enum RewardType { UNKNOWN, // default DRAW, // draw code ASSIGN, // assign winner END, // end game CLIAM // winner cliam } struct Player { uint256 playerID; // Player id(use to affiliate other player) uint256 eth; // player eth balance uint256 mask; // player mask uint256 genTotal; // general total vault uint256 affTotal; // affiliate total vault uint256 laff; // last affiliate id used } struct Round { uint256 roundDeadline; // deadline to end round uint256 claimDeadline; // deadline to claim winners uint256 pot; // pot uint256 blockNumber; // draw block number(last one) RoundState state; // round state uint256 drawCode; // draw code uint256 totalNum; // total number mapping (address => uint256) winnerNum; // winners' number address[] winners; // winners } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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, "SafeMath mul failed"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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, "SafeMath sub failed"); 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, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library MFCoinsCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return (((((_eth).mul(1000000000000000000).mul(2000000000000000000000000000)).add(39999800000250000000000000000000000000000000000000000000000000000)).sqrt()).sub(199999500000000000000000000000000)) / (1000000000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((500000000).mul(_keys.sq()).add(((399999000000000).mul(_keys.mul(1000000000000000000))) / (2) )) / ((1000000000000000000).sq()); } }
calculates unmasked earnings (just calculates, does not update mask) return earnings in wei format/
function calcUnMaskedEarnings(address _addr) private view returns(uint256) { uint256 diffMask = globalMask_.sub(plyr_[_addr].mask); if (diffMask > 0) { return diffMask.mul(balance_[_addr]).div(1 ether); } }
909,834
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/AccessControl.sol"; contract AccessController is AccessControl { bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MANAGER_ROLE, msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor, Ownable { address public immutable override token; bytes32 public immutable override merkleRoot; uint256 public immutable override endTime; // This is a packed array of booleans. mapping(uint256 => uint256) private _claimedBitMap; constructor( address _token, bytes32 _merkleRoot, uint256 _endTime ) public { token = _token; merkleRoot = _merkleRoot; require(block.timestamp < _endTime, "Invalid endTime"); endTime = _endTime; } /** @dev Modifier to check that claim period is active.*/ modifier whenActive() { require(isActive(), "Claim period has ended"); _; } function claim( uint256 _index, address _account, uint256 _amount, bytes32[] calldata merkleProof ) external override whenActive { require(!isClaimed(_index), "Drop already claimed"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(_index, _account, _amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it claimed and send the token. _setClaimed(_index); require(IERC20(token).transfer(_account, _amount), "Transfer failed"); emit Claimed(_index, _account, _amount); } function isClaimed(uint256 _index) public view override returns (bool) { uint256 claimedWordIndex = _index / 256; uint256 claimedBitIndex = _index % 256; uint256 claimedWord = _claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function isActive() public view override returns (bool) { return block.timestamp < endTime; } function recoverERC20(address _tokenAddress, uint256 _tokenAmount) public onlyOwner { IERC20(_tokenAddress).transfer(owner(), _tokenAmount); } function _setClaimed(uint256 _index) private { uint256 claimedWordIndex = _index / 256; uint256 claimedBitIndex = _index % 256; _claimedBitMap[claimedWordIndex] = _claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } } // 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 These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof ) external; // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Returns the block timestamp when claims will end function endTime() external view returns (uint256); // Returns true if the claim period has not ended. function isActive() external view returns (bool); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "./interfaces/IVaultsCoreV1.sol"; import "./interfaces/ILiquidationManagerV1.sol"; import "./interfaces/IAddressProviderV1.sol"; contract VaultsCoreV1 is IVaultsCoreV1, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; uint256 public constant MAX_INT = 2**256 - 1; mapping(address => uint256) public override cumulativeRates; mapping(address => uint256) public override lastRefresh; IAddressProviderV1 public override a; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } modifier onlyVaultOwner(uint256 _vaultId) { require(a.vaultsData().vaultOwner(_vaultId) == msg.sender); _; } modifier onlyConfig() { require(msg.sender == address(a.config())); _; } constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /* Allow smooth upgrading of the vaultscore. @dev this function approves token transfers to the new vaultscore of both stablex and all configured collateral types @param _newVaultsCore address of the new vaultscore */ function upgrade(address _newVaultsCore) public override onlyManager { require(address(_newVaultsCore) != address(0)); require(a.stablex().approve(_newVaultsCore, MAX_INT)); for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; IERC20 asset = IERC20(collateralType); asset.safeApprove(_newVaultsCore, MAX_INT); } } /** Calculate the available income @return available income that has not been minted yet. **/ function availableIncome() public view override returns (uint256) { return a.vaultsData().debt().sub(a.stablex().totalSupply()); } /** Refresh the cumulative rates and debts of all vaults and all collateral types. **/ function refresh() public override { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; refreshCollateral(collateralType); } } /** Initialize the cumulative rates to 1 for a new collateral type. @param _collateralType the address of the new collateral type to be initialized **/ function initializeRates(address _collateralType) public override onlyConfig { require(_collateralType != address(0)); lastRefresh[_collateralType] = now; cumulativeRates[_collateralType] = WadRayMath.ray(); } /** Refresh the cumulative rate of a collateraltype. @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be refreshed. **/ function refreshCollateral(address _collateralType) public override { require(_collateralType != address(0)); require(a.config().collateralIds(_collateralType) != 0); uint256 timestamp = now; uint256 timeElapsed = timestamp.sub(lastRefresh[_collateralType]); _refreshCumulativeRate(_collateralType, timeElapsed); lastRefresh[_collateralType] = timestamp; } /** Internal function to increase the cumulative rate over a specified time period @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be updated @param _timeElapsed the amount of time in seconds to add to the cumulative rate **/ function _refreshCumulativeRate(address _collateralType, uint256 _timeElapsed) internal { uint256 borrowRate = a.config().collateralBorrowRate(_collateralType); uint256 oldCumulativeRate = cumulativeRates[_collateralType]; cumulativeRates[_collateralType] = a.ratesManager().calculateCumulativeRate( borrowRate, oldCumulativeRate, _timeElapsed ); emit CumulativeRateUpdated(_collateralType, _timeElapsed, cumulativeRates[_collateralType]); } /** Deposit an ERC20 token into the vault of the msg.sender as collateral @dev A new vault is created if no vault exists for the `msg.sender` with the specified collateral type. this function used `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _collateralType the address of the collateral type to be deposited @param _amount the amount of tokens to be deposited in WEI. **/ function deposit(address _collateralType, uint256 _amount) public override { require(a.config().collateralIds(_collateralType) != 0); uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender); if (vaultId == 0) { vaultId = a.vaultsData().createVault(_collateralType, msg.sender); } IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(vaultId); a.vaultsData().setCollateralBalance(vaultId, v.collateralBalance.add(_amount)); IERC20 asset = IERC20(v.collateralType); asset.safeTransferFrom(msg.sender, address(this), _amount); emit Deposited(vaultId, _amount, msg.sender); } /** Withdraws ERC20 tokens from a vault. @dev Only te owner of a vault can withdraw collateral from it. `withdraw()` will fail if it would bring the vault below the liquidation treshold. @param _vaultId the ID of the vault from which to withdraw the collateral. @param _amount the amount of ERC20 tokens to be withdrawn in WEI. **/ function withdraw(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(_amount <= v.collateralBalance); uint256 newCollateralBalance = v.collateralBalance.sub(_amount); a.vaultsData().setCollateralBalance(_vaultId, newCollateralBalance); if (v.baseDebt > 0) { //save gas cost when withdrawing from 0 debt vault refreshCollateral(v.collateralType); uint256 newCollateralValue = a.priceFeed().convertFrom(v.collateralType, newCollateralBalance); bool _isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, newCollateralValue, a.vaultsData().vaultDebt(_vaultId) ); require(_isHealthy); } IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, _amount); emit Withdrawn(_vaultId, _amount, msg.sender); } /** Convenience function to withdraw all collateral of a vault @dev Only te owner of a vault can withdraw collateral from it. `withdrawAll()` will fail if the vault has any outstanding debt attached to it. @param _vaultId the ID of the vault from which to withdraw the collateral. **/ function withdrawAll(uint256 _vaultId) public override onlyVaultOwner(_vaultId) { uint256 collateralBalance = a.vaultsData().vaultCollateralBalance(_vaultId); withdraw(_vaultId, collateralBalance); } /** Borrow new StableX (Eg: PAR) tokens from a vault. @dev Only te owner of a vault can borrow from it. `borrow()` will update the outstanding vault debt to the current time before attempting the withdrawal. and will fail if it would bring the vault below the liquidation treshold. @param _vaultId the ID of the vault from which to borrow. @param _amount the amount of borrowed StableX tokens in WEI. **/ function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); //make sure current rate is up to date refreshCollateral(v.collateralType); uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType); uint256 newDebt = _amount; if (originationFeePercentage > 0) { newDebt = newDebt.add(_amount.wadMul(originationFeePercentage)); } // Increment vault borrow balance uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(newDebt, cumulativeRates[v.collateralType]); a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt)); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId); require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType)); bool isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, collateralValue, newVaultDebt ); require(isHealthy); a.stablex().mint(msg.sender, _amount); emit Borrowed(_vaultId, _amount, msg.sender); } /** Convenience function to repay all debt of a vault @dev `repayAll()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the debt. **/ function repayAll(uint256 _vaultId) public override { repay(_vaultId, 2**256 - 1); } /** Repay an outstanding StableX balance to a vault. @dev `repay()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the outstanding debt balance. @param _amount the amount of StableX tokens in WEI to be repaid. **/ function repay(uint256 _vaultId, uint256 _amount) public override nonReentrant { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); // Make sure current rate is up to date refreshCollateral(collateralType); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); // Decrement vault borrow balance if (_amount >= currentVaultDebt) { //full repayment _amount = currentVaultDebt; //only pay back what's outstanding } _reduceVaultDebt(_vaultId, _amount); a.stablex().burn(msg.sender, _amount); emit Repaid(_vaultId, _amount, msg.sender); } /** Internal helper function to reduce the debt of a vault. @dev assumes cumulative rates for the vault's collateral type are up to date. please call `refreshCollateral()` before calling this function. @param _vaultId the ID of the vault for which to reduce the debt. @param _amount the amount of debt to be reduced. **/ function _reduceVaultDebt(uint256 _vaultId, uint256 _amount) internal { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); uint256 remainder = currentVaultDebt.sub(_amount); uint256 cumulativeRate = cumulativeRates[collateralType]; if (remainder == 0) { a.vaultsData().setBaseDebt(_vaultId, 0); } else { uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(remainder, cumulativeRate); a.vaultsData().setBaseDebt(_vaultId, newBaseDebt); } } /** Liquidate a vault that is below the liquidation treshold by repaying it's outstanding debt. @dev `liquidate()` will update the outstanding vault debt to the current time and pay a `liquidationBonus` to the liquidator. `liquidate()` can be called by anyone. @param _vaultId the ID of the vault to be liquidated. **/ function liquidate(uint256 _vaultId) public override nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); refreshCollateral(v.collateralType); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); require( !ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, collateralValue, currentVaultDebt ) ); uint256 discountedValue = ILiquidationManagerV1(address(a.liquidationManager())).applyLiquidationDiscount( collateralValue ); uint256 collateralToReceive; uint256 stableXToPay = currentVaultDebt; if (discountedValue < currentVaultDebt) { //Insurance Case uint256 insuranceAmount = currentVaultDebt.sub(discountedValue); require(a.stablex().balanceOf(address(this)) >= insuranceAmount); a.stablex().burn(address(this), insuranceAmount); emit InsurancePaid(_vaultId, insuranceAmount, msg.sender); collateralToReceive = v.collateralBalance; stableXToPay = currentVaultDebt.sub(insuranceAmount); } else { collateralToReceive = a.priceFeed().convertTo(v.collateralType, currentVaultDebt); collateralToReceive = collateralToReceive.add( ILiquidationManagerV1(address(a.liquidationManager())).liquidationBonus(collateralToReceive) ); } // reduce the vault debt to 0 _reduceVaultDebt(_vaultId, currentVaultDebt); a.stablex().burn(msg.sender, stableXToPay); // send the collateral to the liquidator a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.sub(collateralToReceive)); IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, collateralToReceive); emit Liquidated(_vaultId, stableXToPay, collateralToReceive, v.owner, msg.sender); } } // 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 Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.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 { using SafeMath for uint256; uint256 internal constant _WAD = 1e18; uint256 internal constant _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _RAY / 2; uint256 internal constant _WAD_RAY_RATIO = 1e9; function ray() internal pure returns (uint256) { return _RAY; } function wad() internal pure returns (uint256) { return _WAD; } function halfRay() internal pure returns (uint256) { return _HALF_RAY; } function halfWad() internal pure returns (uint256) { return _HALF_WAD; } function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return _HALF_WAD.add(a.mul(b)).div(_WAD); } function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(_WAD)).div(b); } function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { return _HALF_RAY.add(a.mul(b)).div(_RAY); } function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 halfB = b / 2; return halfB.add(a.mul(_RAY)).div(b); } function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = _WAD_RAY_RATIO / 2; return halfRatio.add(a).div(_WAD_RAY_RATIO); } function wadToRay(uint256 a) internal pure returns (uint256) { return a.mul(_WAD_RAY_RATIO); } /** * @dev calculates x^n, in ray. The code uses the ModExp precompile * @param x base * @param n exponent * @return z = x^n, in ray */ function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : _RAY; for (n /= 2; n != 0; n /= 2) { x = rayMul(x, x); if (n % 2 != 0) { z = rayMul(z, x); } } } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IVaultsCoreV1 { event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner); event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender); event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender); event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender); event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender); event Liquidated( uint256 indexed vaultId, uint256 debtRepaid, uint256 collateralLiquidated, address indexed owner, address indexed sender ); event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0 event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender); function deposit(address _collateralType, uint256 _amount) external; function withdraw(uint256 _vaultId, uint256 _amount) external; function withdrawAll(uint256 _vaultId) external; function borrow(uint256 _vaultId, uint256 _amount) external; function repayAll(uint256 _vaultId) external; function repay(uint256 _vaultId, uint256 _amount) external; function liquidate(uint256 _vaultId) external; //Refresh function initializeRates(address _collateralType) external; function refresh() external; function refreshCollateral(address collateralType) external; //upgrade function upgrade(address _newVaultsCore) external; //Read only function a() external view returns (IAddressProviderV1); function availableIncome() external view returns (uint256); function cumulativeRates(address _collateralType) external view returns (uint256); function lastRefresh(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface ILiquidationManagerV1 { function a() external view returns (IAddressProviderV1); function calculateHealthFactor( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) external view returns (uint256 healthFactor); function liquidationBonus(uint256 _amount) external view returns (uint256 bonus); function applyLiquidationDiscount(uint256 _amount) external view returns (uint256 discountedAmount); function isHealthy( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IConfigProviderV1.sol'; import './ILiquidationManagerV1.sol'; import './IVaultsCoreV1.sol'; import '../../interfaces/IVaultsCore.sol'; import '../../interfaces/IAccessController.sol'; import '../../interfaces/ISTABLEX.sol'; import '../../interfaces/IPriceFeed.sol'; import '../../interfaces/IRatesManager.sol'; import '../../interfaces/IVaultsDataProvider.sol'; import '../../interfaces/IFeeDistributor.sol'; interface IAddressProviderV1 { function setAccessController(IAccessController _controller) external; function setConfigProvider(IConfigProviderV1 _config) external; function setVaultsCore(IVaultsCoreV1 _core) external; function setStableX(ISTABLEX _stablex) external; function setRatesManager(IRatesManager _ratesManager) external; function setPriceFeed(IPriceFeed _priceFeed) external; function setLiquidationManager(ILiquidationManagerV1 _liquidationManager) external; function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external; function setFeeDistributor(IFeeDistributor _feeDistributor) external; function controller() external view returns (IAccessController); function config() external view returns (IConfigProviderV1); function core() external view returns (IVaultsCoreV1); function stablex() external view returns (ISTABLEX); function ratesManager() external view returns (IRatesManager); function priceFeed() external view returns (IPriceFeed); function liquidationManager() external view returns (ILiquidationManagerV1); function vaultsData() external view returns (IVaultsDataProvider); function feeDistributor() external view returns (IFeeDistributor); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IConfigProviderV1 { struct CollateralConfig { address collateralType; uint256 debtLimit; uint256 minCollateralRatio; uint256 borrowRate; uint256 originationFee; } event CollateralUpdated( address indexed collateralType, uint256 debtLimit, uint256 minCollateralRatio, uint256 borrowRate, uint256 originationFee ); event CollateralRemoved(address indexed collateralType); function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee ) external; function removeCollateral(address _collateralType) external; function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external; function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external; function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external; function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external; function setLiquidationBonus(uint256 _bonus) external; function a() external view returns (IAddressProviderV1); function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory); function collateralIds(address _collateralType) external view returns (uint256); function numCollateralConfigs() external view returns (uint256); function liquidationBonus() external view returns (uint256); function collateralDebtLimit(address _collateralType) external view returns (uint256); function collateralMinCollateralRatio(address _collateralType) external view returns (uint256); function collateralBorrowRate(address _collateralType) external view returns (uint256); function collateralOriginationFee(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../interfaces/IWETH.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; interface IVaultsCore { event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner); event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender); event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender); event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender); event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender); event Liquidated( uint256 indexed vaultId, uint256 debtRepaid, uint256 collateralLiquidated, address indexed owner, address indexed sender ); event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender); function deposit(address _collateralType, uint256 _amount) external; function depositETH() external payable; function depositByVaultId(uint256 _vaultId, uint256 _amount) external; function depositETHByVaultId(uint256 _vaultId) external payable; function depositAndBorrow( address _collateralType, uint256 _depositAmount, uint256 _borrowAmount ) external; function depositETHAndBorrow(uint256 _borrowAmount) external payable; function withdraw(uint256 _vaultId, uint256 _amount) external; function withdrawETH(uint256 _vaultId, uint256 _amount) external; function borrow(uint256 _vaultId, uint256 _amount) external; function repayAll(uint256 _vaultId) external; function repay(uint256 _vaultId, uint256 _amount) external; function liquidate(uint256 _vaultId) external; function liquidatePartial(uint256 _vaultId, uint256 _amount) external; function upgrade(address payable _newVaultsCore) external; function acceptUpgrade(address payable _oldVaultsCore) external; function setDebtNotifier(IDebtNotifier _debtNotifier) external; //Read only function a() external view returns (IAddressProvider); function WETH() external view returns (IWETH); function debtNotifier() external view returns (IDebtNotifier); function state() external view returns (IVaultsCoreState); function cumulativeRates(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAccessController { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function MANAGER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IAddressProvider.sol"; interface ISTABLEX is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function a() external view returns (IAddressProvider); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../chainlink/AggregatorV3Interface.sol"; import "../interfaces/IAddressProvider.sol"; interface IPriceFeed { event OracleUpdated(address indexed asset, address oracle, address sender); event EurOracleUpdated(address oracle, address sender); function setAssetOracle(address _asset, address _oracle) external; function setEurOracle(address _oracle) external; function a() external view returns (IAddressProvider); function assetOracles(address _asset) external view returns (AggregatorV3Interface); function eurOracle() external view returns (AggregatorV3Interface); function getAssetPrice(address _asset) external view returns (uint256); function convertFrom(address _asset, uint256 _amount) external view returns (uint256); function convertTo(address _asset, uint256 _amount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IRatesManager { function a() external view returns (IAddressProvider); //current annualized borrow rate function annualizedBorrowRate(uint256 _currentBorrowRate) external pure returns (uint256); //uses current cumulative rate to calculate totalDebt based on baseDebt at time T0 function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) external pure returns (uint256); //uses current cumulative rate to calculate baseDebt at time T0 function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) external pure returns (uint256); //calculate a new cumulative rate function calculateCumulativeRate( uint256 _borrowRate, uint256 _cumulativeRate, uint256 _timeElapsed ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IVaultsDataProvider { struct Vault { // borrowedType support USDX / PAR address collateralType; address owner; uint256 collateralBalance; uint256 baseDebt; uint256 createdAt; } //Write function createVault(address _collateralType, address _owner) external returns (uint256); function setCollateralBalance(uint256 _id, uint256 _balance) external; function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external; // Read function a() external view returns (IAddressProvider); function baseDebt(address _collateralType) external view returns (uint256); function vaultCount() external view returns (uint256); function vaults(uint256 _id) external view returns (Vault memory); function vaultOwner(uint256 _id) external view returns (address); function vaultCollateralType(uint256 _id) external view returns (address); function vaultCollateralBalance(uint256 _id) external view returns (uint256); function vaultBaseDebt(uint256 _id) external view returns (uint256); function vaultId(address _collateralType, address _owner) external view returns (uint256); function vaultExists(uint256 _id) external view returns (bool); function vaultDebt(uint256 _vaultId) external view returns (uint256); function debt() external view returns (uint256); function collateralDebt(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IFeeDistributor { event PayeeAdded(address indexed account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); function release() external; function changePayees(address[] memory _payees, uint256[] memory _shares) external; function a() external view returns (IAddressProvider); function lastReleasedAt() external view returns (uint256); function getPayees() external view returns (address[] memory); function totalShares() external view returns (uint256); function shares(address payee) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./IAccessController.sol"; import "./IConfigProvider.sol"; import "./ISTABLEX.sol"; import "./IPriceFeed.sol"; import "./IRatesManager.sol"; import "./ILiquidationManager.sol"; import "./IVaultsCore.sol"; import "./IVaultsDataProvider.sol"; import "./IFeeDistributor.sol"; interface IAddressProvider { function setAccessController(IAccessController _controller) external; function setConfigProvider(IConfigProvider _config) external; function setVaultsCore(IVaultsCore _core) external; function setStableX(ISTABLEX _stablex) external; function setRatesManager(IRatesManager _ratesManager) external; function setPriceFeed(IPriceFeed _priceFeed) external; function setLiquidationManager(ILiquidationManager _liquidationManager) external; function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external; function setFeeDistributor(IFeeDistributor _feeDistributor) external; function controller() external view returns (IAccessController); function config() external view returns (IConfigProvider); function core() external view returns (IVaultsCore); function stablex() external view returns (ISTABLEX); function ratesManager() external view returns (IRatesManager); function priceFeed() external view returns (IPriceFeed); function liquidationManager() external view returns (ILiquidationManager); function vaultsData() external view returns (IVaultsDataProvider); function feeDistributor() external view returns (IFeeDistributor); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./IAddressProvider.sol"; import "../v1/interfaces/IVaultsCoreV1.sol"; interface IVaultsCoreState { event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0 function initializeRates(address _collateralType) external; function refresh() external; function refreshCollateral(address collateralType) external; function syncState(IVaultsCoreState _stateAddress) external; function syncStateFromV1(IVaultsCoreV1 _core) external; //Read only function a() external view returns (IAddressProvider); function availableIncome() external view returns (uint256); function cumulativeRates(address _collateralType) external view returns (uint256); function lastRefresh(address _collateralType) external view returns (uint256); function synced() external view returns (bool); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; import './ISupplyMiner.sol'; interface IDebtNotifier { function debtChanged(uint256 _vaultId) external; function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) external; function a() external view returns (IGovernanceAddressProvider); function collateralSupplyMinerMapping(address collateral) external view returns (ISupplyMiner); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface IConfigProvider { struct CollateralConfig { address collateralType; uint256 debtLimit; uint256 liquidationRatio; uint256 minCollateralRatio; uint256 borrowRate; uint256 originationFee; uint256 liquidationBonus; uint256 liquidationFee; } event CollateralUpdated( address indexed collateralType, uint256 debtLimit, uint256 liquidationRatio, uint256 minCollateralRatio, uint256 borrowRate, uint256 originationFee, uint256 liquidationBonus, uint256 liquidationFee ); event CollateralRemoved(address indexed collateralType); function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _liquidationRatio, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee, uint256 _liquidationBonus, uint256 _liquidationFee ) external; function removeCollateral(address _collateralType) external; function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external; function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) external; function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external; function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external; function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external; function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) external; function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) external; function setMinVotingPeriod(uint256 _minVotingPeriod) external; function setMaxVotingPeriod(uint256 _maxVotingPeriod) external; function setVotingQuorum(uint256 _votingQuorum) external; function setProposalThreshold(uint256 _proposalThreshold) external; function a() external view returns (IAddressProvider); function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory); function collateralIds(address _collateralType) external view returns (uint256); function numCollateralConfigs() external view returns (uint256); function minVotingPeriod() external view returns (uint256); function maxVotingPeriod() external view returns (uint256); function votingQuorum() external view returns (uint256); function proposalThreshold() external view returns (uint256); function collateralDebtLimit(address _collateralType) external view returns (uint256); function collateralLiquidationRatio(address _collateralType) external view returns (uint256); function collateralMinCollateralRatio(address _collateralType) external view returns (uint256); function collateralBorrowRate(address _collateralType) external view returns (uint256); function collateralOriginationFee(address _collateralType) external view returns (uint256); function collateralLiquidationBonus(address _collateralType) external view returns (uint256); function collateralLiquidationFee(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; interface ILiquidationManager { function a() external view returns (IAddressProvider); function calculateHealthFactor( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) external view returns (uint256 healthFactor); function liquidationBonus(address _collateralType, uint256 _amount) external view returns (uint256 bonus); function applyLiquidationDiscount(address _collateralType, uint256 _amount) external view returns (uint256 discountedAmount); function isHealthy( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IGovernorAlpha.sol'; import './ITimelock.sol'; import './IVotingEscrow.sol'; import '../../interfaces/IAccessController.sol'; import '../../interfaces/IAddressProvider.sol'; import '../../liquidityMining/interfaces/IMIMO.sol'; import '../../liquidityMining/interfaces/IDebtNotifier.sol'; interface IGovernanceAddressProvider { function setParallelAddressProvider(IAddressProvider _parallel) external; function setMIMO(IMIMO _mimo) external; function setDebtNotifier(IDebtNotifier _debtNotifier) external; function setGovernorAlpha(IGovernorAlpha _governorAlpha) external; function setTimelock(ITimelock _timelock) external; function setVotingEscrow(IVotingEscrow _votingEscrow) external; function controller() external view returns (IAccessController); function parallel() external view returns (IAddressProvider); function mimo() external view returns (IMIMO); function debtNotifier() external view returns (IDebtNotifier); function governorAlpha() external view returns (IGovernorAlpha); function timelock() external view returns (ITimelock); function votingEscrow() external view returns (IVotingEscrow); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface ISupplyMiner { function baseDebtChanged(address user, uint256 newBaseDebt) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface IGovernorAlpha { /// @notice Possible states that a proposal may be in enum ProposalState { Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } struct Proposal { // Unique id for looking up a proposal uint256 id; // Creator of the proposal address proposer; // The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; // the ordered list of target addresses for calls to be made address[] targets; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint256[] values; // The ordered list of function signatures to be called string[] signatures; // The ordered list of calldata to be passed to each call bytes[] calldatas; // The timestamp at which voting begins: holders must delegate their votes prior to this timestamp uint256 startTime; // The timestamp at which voting ends: votes must be cast prior to this timestamp uint256 endTime; // Current number of votes in favor of this proposal uint256 forVotes; // Current number of votes in opposition to this proposal uint256 againstVotes; // Flag marking whether the proposal has been canceled bool canceled; // Flag marking whether the proposal has been executed bool executed; // Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { // Whether or not a vote has been cast bool hasVoted; // Whether or not the voter supports the proposal bool support; // The number of votes the voter had, which were cast uint256 votes; } /// @notice An event emitted when a new proposal is created event ProposalCreated( uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startTime, uint256 endTime, string description ); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint256 id, uint256 eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, uint256 endTime ) external returns (uint256); function queue(uint256 proposalId) external; function execute(uint256 proposalId) external payable; function cancel(uint256 proposalId) external; function castVote(uint256 proposalId, bool support) external; function getActions(uint256 proposalId) external view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ); function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory); function state(uint256 proposalId) external view returns (ProposalState); function quorumVotes() external view returns (uint256); function proposalThreshold() external view returns (uint256); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; interface ITimelock { event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); function acceptAdmin() external; function queueTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external returns (bytes32); function cancelTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external; function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable returns (bytes memory); function delay() external view returns (uint256); function GRACE_PERIOD() external view returns (uint256); function queuedTransactions(bytes32 hash) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '../../liquidityMining/interfaces/IGenericMiner.sol'; interface IVotingEscrow { enum LockAction { CREATE_LOCK, INCREASE_LOCK_AMOUNT, INCREASE_LOCK_TIME } struct LockedBalance { uint256 amount; uint256 end; } /** Shared Events */ event Deposit(address indexed provider, uint256 value, uint256 locktime, LockAction indexed action, uint256 ts); event Withdraw(address indexed provider, uint256 value, uint256 ts); event Expired(); function createLock(uint256 _value, uint256 _unlockTime) external; function increaseLockAmount(uint256 _value) external; function increaseLockLength(uint256 _unlockTime) external; function withdraw() external; function expireContract() external; function setMiner(IGenericMiner _miner) external; function setMinimumLockTime(uint256 _minimumLockTime) external; function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function balanceOfAt(address _owner, uint256 _blockTime) external view returns (uint256); function stakingToken() external view returns (IERC20); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IMIMO is IERC20 { function burn(address account, uint256 amount) external; function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '@openzeppelin/contracts/math/SafeMath.sol'; import '../../interfaces/IAddressProvider.sol'; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; interface IGenericMiner { struct UserInfo { uint256 stake; uint256 accAmountPerShare; // User's accAmountPerShare } /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event StakeIncreased(address indexed user, uint256 stake); /// @dev This emit when a users' productivity has changed /// It emits with the user's address and the the value after the change. event StakeDecreased(address indexed user, uint256 stake); function releaseMIMO(address _user) external; function a() external view returns (IGovernanceAddressProvider); function stake(address _user) external view returns (uint256); function pendingMIMO(address _user) external view returns (uint256); function totalStake() external view returns (uint256); function userInfo(address _user) external view returns (UserInfo memory); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IVaultsDataProviderV1.sol"; import "./interfaces/IAddressProviderV1.sol"; contract VaultsDataProviderV1 is IVaultsDataProviderV1 { using SafeMath for uint256; IAddressProviderV1 public override a; uint256 public override vaultCount = 0; mapping(address => uint256) public override baseDebt; mapping(uint256 => Vault) private _vaults; mapping(address => mapping(address => uint256)) private _vaultOwners; modifier onlyVaultsCore() { require(msg.sender == address(a.core()), "Caller is not VaultsCore"); _; } constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Opens a new vault. @dev only the vaultsCore module can call this function @param _collateralType address to the collateral asset e.g. WETH @param _owner the owner of the new vault. */ function createVault(address _collateralType, address _owner) public override onlyVaultsCore returns (uint256) { require(_collateralType != address(0)); require(_owner != address(0)); uint256 newId = ++vaultCount; require(_collateralType != address(0), "collateralType unknown"); Vault memory v = Vault({ collateralType: _collateralType, owner: _owner, collateralBalance: 0, baseDebt: 0, createdAt: block.timestamp }); _vaults[newId] = v; _vaultOwners[_owner][_collateralType] = newId; return newId; } /** Set the collateral balance of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the collateral balance will be updated @param _balance the new balance of the vault. */ function setCollateralBalance(uint256 _id, uint256 _balance) public override onlyVaultsCore { require(vaultExists(_id), "Vault not found."); Vault storage v = _vaults[_id]; v.collateralBalance = _balance; } /** Set the base debt of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the base debt will be updated @param _newBaseDebt the new base debt of the vault. */ function setBaseDebt(uint256 _id, uint256 _newBaseDebt) public override onlyVaultsCore { Vault storage _vault = _vaults[_id]; if (_newBaseDebt > _vault.baseDebt) { uint256 increase = _newBaseDebt.sub(_vault.baseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].add(increase); } else { uint256 decrease = _vault.baseDebt.sub(_newBaseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].sub(decrease); } _vault.baseDebt = _newBaseDebt; } /** Get a vault by vault ID. @param _id The vault's ID to be retrieved */ function vaults(uint256 _id) public view override returns (Vault memory) { Vault memory v = _vaults[_id]; return v; } /** Get the owner of a vault. @param _id the ID of the vault @return owner of the vault */ function vaultOwner(uint256 _id) public view override returns (address) { return _vaults[_id].owner; } /** Get the collateral type of a vault. @param _id the ID of the vault @return address for the collateral type of the vault */ function vaultCollateralType(uint256 _id) public view override returns (address) { return _vaults[_id].collateralType; } /** Get the collateral balance of a vault. @param _id the ID of the vault @return collateral balance of the vault */ function vaultCollateralBalance(uint256 _id) public view override returns (uint256) { return _vaults[_id].collateralBalance; } /** Get the base debt of a vault. @param _id the ID of the vault @return base debt of the vault */ function vaultBaseDebt(uint256 _id) public view override returns (uint256) { return _vaults[_id].baseDebt; } /** Retrieve the vault id for a specified owner and collateral type. @dev returns 0 for non-existing vaults @param _collateralType address of the collateral type (Eg: WETH) @param _owner address of the owner of the vault @return vault id of the vault or 0 */ function vaultId(address _collateralType, address _owner) public view override returns (uint256) { return _vaultOwners[_owner][_collateralType]; } /** Checks if a specified vault exists. @param _id the ID of the vault @return boolean if the vault exists */ function vaultExists(uint256 _id) public view override returns (bool) { Vault memory v = _vaults[_id]; return v.collateralType != address(0); } /** Calculated the total outstanding debt for all vaults and all collateral types. @dev uses the existing cumulative rate. Call `refresh()` on `VaultsCore` to make sure it's up to date. @return total debt of the platform */ function debt() public view override returns (uint256) { uint256 total = 0; for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; total = total.add(collateralDebt(collateralType)); } return total; } /** Calculated the total outstanding debt for all vaults of a specific collateral type. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _collateralType address of the collateral type (Eg: WETH) @return total debt of the platform of one collateral type */ function collateralDebt(address _collateralType) public view override returns (uint256) { return a.ratesManager().calculateDebt(baseDebt[_collateralType], a.core().cumulativeRates(_collateralType)); } /** Calculated the total outstanding debt for a specific vault. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _vaultId the ID of the vault @return total debt of one vault */ function vaultDebt(uint256 _vaultId) public view override returns (uint256) { IVaultsDataProviderV1.Vault memory v = vaults(_vaultId); return a.ratesManager().calculateDebt(v.baseDebt, a.core().cumulativeRates(v.collateralType)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IVaultsDataProviderV1 { struct Vault { // borrowedType support USDX / PAR address collateralType; address owner; uint256 collateralBalance; uint256 baseDebt; uint256 createdAt; } //Write function createVault(address _collateralType, address _owner) external returns (uint256); function setCollateralBalance(uint256 _id, uint256 _balance) external; function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external; function a() external view returns (IAddressProviderV1); // Read function baseDebt(address _collateralType) external view returns (uint256); function vaultCount() external view returns (uint256); function vaults(uint256 _id) external view returns (Vault memory); function vaultOwner(uint256 _id) external view returns (address); function vaultCollateralType(uint256 _id) external view returns (address); function vaultCollateralBalance(uint256 _id) external view returns (uint256); function vaultBaseDebt(uint256 _id) external view returns (uint256); function vaultId(address _collateralType, address _owner) external view returns (uint256); function vaultExists(uint256 _id) external view returns (bool); function vaultDebt(uint256 _vaultId) external view returns (uint256); function debt() external view returns (uint256); function collateralDebt(address _collateralType) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "./interfaces/IAddressProviderV1.sol"; import "./interfaces/IConfigProviderV1.sol"; import "./interfaces/ILiquidationManagerV1.sol"; contract LiquidationManagerV1 is ILiquidationManagerV1, ReentrancyGuard { using SafeMath for uint256; using WadRayMath for uint256; IAddressProviderV1 public override a; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // 1 uint256 public constant FULL_LIQUIDIATION_TRESHOLD = 100e18; // 100 USDX, vaults below 100 USDX can be liquidated in full constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Check if the health factor is above or equal to 1. @param _collateralType address of the collateral type @param _collateralValue value of the collateral in stableX currency @param _vaultDebt outstanding debt to which the collateral balance shall be compared @return boolean if the health factor is >= 1. */ function isHealthy( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) public view override returns (bool) { uint256 healthFactor = calculateHealthFactor(_collateralType, _collateralValue, _vaultDebt); return healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** Calculate the healthfactor of a debt balance @param _collateralType address of the collateral type @param _collateralValue value of the collateral in stableX currency @param _vaultDebt outstanding debt to which the collateral balance shall be compared @return healthFactor */ function calculateHealthFactor( address _collateralType, uint256 _collateralValue, uint256 _vaultDebt ) public view override returns (uint256 healthFactor) { if (_vaultDebt == 0) return WadRayMath.wad(); // CurrentCollateralizationRatio = deposited ETH in USD / debt in USD uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt); // Healthfactor = CurrentCollateralizationRatio / MinimumCollateralizationRatio uint256 collateralId = a.config().collateralIds(_collateralType); require(collateralId > 0, "collateral not supported"); uint256 minRatio = a.config().collateralConfigs(collateralId).minCollateralRatio; if (minRatio > 0) { return collateralizationRatio.wadDiv(minRatio); } return 1e18; // 1 } /** Calculate the liquidation bonus for a specified amount @param _amount amount for which the liquidation bonus shall be calculated @return bonus the liquidation bonus to pay out */ function liquidationBonus(uint256 _amount) public view override returns (uint256 bonus) { return _amount.wadMul(IConfigProviderV1(address(a.config())).liquidationBonus()); } /** Apply the liquidation bonus to a balance as a discount. @param _amount the balance on which to apply to liquidation bonus as a discount. @return discountedAmount */ function applyLiquidationDiscount(uint256 _amount) public view override returns (uint256 discountedAmount) { return _amount.wadDiv(IConfigProviderV1(address(a.config())).liquidationBonus().add(WadRayMath.wad())); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IAccessController.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/ISTABLEX.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IRatesManager.sol"; import "../interfaces/IVaultsDataProvider.sol"; import "./interfaces/IConfigProviderV1.sol"; import "./interfaces/ILiquidationManagerV1.sol"; import "./interfaces/IVaultsCoreV1.sol"; contract AddressProviderV1 is IAddressProvider { IAccessController public override controller; IConfigProvider public override config; IVaultsCore public override core; ISTABLEX public override stablex; IRatesManager public override ratesManager; IPriceFeed public override priceFeed; ILiquidationManager public override liquidationManager; IVaultsDataProvider public override vaultsData; IFeeDistributor public override feeDistributor; constructor(IAccessController _controller) public { controller = _controller; } modifier onlyManager() { require(controller.hasRole(controller.MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } function setAccessController(IAccessController _controller) public override onlyManager { require(address(_controller) != address(0)); controller = _controller; } function setConfigProvider(IConfigProvider _config) public override onlyManager { require(address(_config) != address(0)); config = _config; } function setVaultsCore(IVaultsCore _core) public override onlyManager { require(address(_core) != address(0)); core = _core; } function setStableX(ISTABLEX _stablex) public override onlyManager { require(address(_stablex) != address(0)); stablex = _stablex; } function setRatesManager(IRatesManager _ratesManager) public override onlyManager { require(address(_ratesManager) != address(0)); ratesManager = _ratesManager; } function setLiquidationManager(ILiquidationManager _liquidationManager) public override onlyManager { require(address(_liquidationManager) != address(0)); liquidationManager = _liquidationManager; } function setPriceFeed(IPriceFeed _priceFeed) public override onlyManager { require(address(_priceFeed) != address(0)); priceFeed = _priceFeed; } function setVaultsDataProvider(IVaultsDataProvider _vaultsData) public override onlyManager { require(address(_vaultsData) != address(0)); vaultsData = _vaultsData; } function setFeeDistributor(IFeeDistributor _feeDistributor) public override onlyManager { require(address(_feeDistributor) != address(0)); feeDistributor = _feeDistributor; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../libraries/WadRayMath.sol"; import "./interfaces/IConfigProviderV1.sol"; import "./interfaces/IAddressProviderV1.sol"; import "./interfaces/IVaultsCoreV1.sol"; contract ConfigProviderV1 is IConfigProviderV1 { IAddressProviderV1 public override a; mapping(uint256 => CollateralConfig) private _collateralConfigs; //indexing starts at 1 mapping(address => uint256) public override collateralIds; uint256 public override numCollateralConfigs; uint256 public override liquidationBonus = 5e16; // 5% constructor(IAddressProviderV1 _addresses) public { a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** Creates or overwrites an existing config for a collateral type @param _collateralType address of the collateral type @param _debtLimit the debt ceiling for the collateral type @param _minCollateralRatio the minimum ratio to maintain to avoid liquidation @param _borrowRate the borrowing rate specified in 1 second interval in RAY accuracy. @param _originationFee an optional origination fee for newly created debt. Can be 0. */ function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee ) public override onlyManager { require(address(_collateralType) != address(0)); if (collateralIds[_collateralType] == 0) { //new collateral IVaultsCoreV1(address(a.core())).initializeRates(_collateralType); CollateralConfig memory config = CollateralConfig({ collateralType: _collateralType, debtLimit: _debtLimit, minCollateralRatio: _minCollateralRatio, borrowRate: _borrowRate, originationFee: _originationFee }); numCollateralConfigs++; _collateralConfigs[numCollateralConfigs] = config; collateralIds[_collateralType] = numCollateralConfigs; } else { // Update collateral config IVaultsCoreV1(address(a.core())).refreshCollateral(_collateralType); uint256 id = collateralIds[_collateralType]; _collateralConfigs[id].collateralType = _collateralType; _collateralConfigs[id].debtLimit = _debtLimit; _collateralConfigs[id].minCollateralRatio = _minCollateralRatio; _collateralConfigs[id].borrowRate = _borrowRate; _collateralConfigs[id].originationFee = _originationFee; } emit CollateralUpdated(_collateralType, _debtLimit, _minCollateralRatio, _borrowRate, _originationFee); } function _emitUpdateEvent(address _collateralType) internal { emit CollateralUpdated( _collateralType, _collateralConfigs[collateralIds[_collateralType]].debtLimit, _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio, _collateralConfigs[collateralIds[_collateralType]].borrowRate, _collateralConfigs[collateralIds[_collateralType]].originationFee ); } /** Remove the config for a collateral type @param _collateralType address of the collateral type */ function removeCollateral(address _collateralType) public override onlyManager { uint256 id = collateralIds[_collateralType]; require(id != 0, "collateral does not exist"); collateralIds[_collateralType] = 0; _collateralConfigs[id] = _collateralConfigs[numCollateralConfigs]; //move last entry forward collateralIds[_collateralConfigs[id].collateralType] = id; //update id for last entry delete _collateralConfigs[numCollateralConfigs]; numCollateralConfigs--; emit CollateralRemoved(_collateralType); } /** Sets the debt limit for a collateral type @param _collateralType address of the collateral type @param _debtLimit the new debt limit */ function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].debtLimit = _debtLimit; _emitUpdateEvent(_collateralType); } /** Sets the minimum collateralization ratio for a collateral type @dev this is the liquidation treshold under which a vault is considered open for liquidation. @param _collateralType address of the collateral type @param _minCollateralRatio the new minimum collateralization ratio */ function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio = _minCollateralRatio; _emitUpdateEvent(_collateralType); } /** Sets the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type @param _borrowRate the new borrowing rate for a 1 sec interval */ function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) public override onlyManager { IVaultsCoreV1(address(a.core())).refreshCollateral(_collateralType); _collateralConfigs[collateralIds[_collateralType]].borrowRate = _borrowRate; _emitUpdateEvent(_collateralType); } /** Sets the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type @param _originationFee new origination fee in WAD */ function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].originationFee = _originationFee; _emitUpdateEvent(_collateralType); } /** Get the debt limit for a collateral type @dev this is a platform wide limit for new debt issuance against a specific collateral type @param _collateralType address of the collateral type */ function collateralDebtLimit(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].debtLimit; } /** Get the minimum collateralization ratio for a collateral type @dev this is the liquidation treshold under which a vault is considered open for liquidation. @param _collateralType address of the collateral type */ function collateralMinCollateralRatio(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio; } /** Get the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type */ function collateralBorrowRate(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].borrowRate; } /** Get the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralOriginationFee(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].originationFee; } /** Set the platform wide incentive for liquidations. @dev the liquidation bonus is specified in WAD @param _bonus the liquidation bonus to be paid to liquidators */ function setLiquidationBonus(uint256 _bonus) public override onlyManager { liquidationBonus = _bonus; } /** Retreives the entire config for a specific config id. @param _id the ID of the conifg to be returned */ function collateralConfigs(uint256 _id) public view override returns (CollateralConfig memory) { require(_id <= numCollateralConfigs, "Invalid config id"); return _collateralConfigs[_id]; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../v1/interfaces/IConfigProviderV1.sol"; import "../v1/interfaces/IVaultsCoreV1.sol"; import "../v1/interfaces/IFeeDistributorV1.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../interfaces/ILiquidationManager.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/IFeeDistributor.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; contract Upgrade { using SafeMath for uint256; uint256 public constant LIQUIDATION_BONUS = 5e16; // 5% IAddressProvider public a; IVaultsCore public core; IVaultsCoreState public coreState; ILiquidationManager public liquidationManager; IConfigProvider public config; IFeeDistributor public feeDistributor; IDebtNotifier public debtNotifier; IPriceFeed public priceFeed; address public bpool; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } constructor( IAddressProvider _addresses, IVaultsCore _core, IVaultsCoreState _coreState, ILiquidationManager _liquidationManager, IConfigProvider _config, IFeeDistributor _feeDistributor, IDebtNotifier _debtNotifier, IPriceFeed _priceFeed, address _bpool ) public { require(address(_addresses) != address(0)); require(address(_core) != address(0)); require(address(_coreState) != address(0)); require(address(_liquidationManager) != address(0)); require(address(_config) != address(0)); require(address(_feeDistributor) != address(0)); require(address(_debtNotifier) != address(0)); require(address(_priceFeed) != address(0)); require(_bpool != address(0)); a = _addresses; core = _core; coreState = _coreState; liquidationManager = _liquidationManager; config = _config; feeDistributor = _feeDistributor; debtNotifier = _debtNotifier; priceFeed = _priceFeed; bpool = _bpool; } function upgrade() public onlyManager { IConfigProviderV1 oldConfig = IConfigProviderV1(address(a.config())); IPriceFeed oldPriceFeed = IPriceFeed(address(a.priceFeed())); IVaultsCoreV1 oldCore = IVaultsCoreV1(address(a.core())); IFeeDistributorV1 oldFeeDistributor = IFeeDistributorV1(address(a.feeDistributor())); bytes32 MINTER_ROLE = a.controller().MINTER_ROLE(); bytes32 MANAGER_ROLE = a.controller().MANAGER_ROLE(); bytes32 DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000; a.controller().grantRole(MANAGER_ROLE, address(this)); a.controller().grantRole(MINTER_ROLE, address(core)); a.controller().grantRole(MINTER_ROLE, address(feeDistributor)); oldCore.refresh(); if (oldCore.availableIncome() > 0) { oldFeeDistributor.release(); } a.controller().revokeRole(MINTER_ROLE, address(a.core())); a.controller().revokeRole(MINTER_ROLE, address(a.feeDistributor())); oldCore.upgrade(payable(address(core))); a.setVaultsCore(core); a.setConfigProvider(config); a.setLiquidationManager(liquidationManager); a.setFeeDistributor(feeDistributor); a.setPriceFeed(priceFeed); priceFeed.setEurOracle(address(oldPriceFeed.eurOracle())); uint256 numCollateralConfigs = oldConfig.numCollateralConfigs(); for (uint256 i = 1; i <= numCollateralConfigs; i++) { IConfigProviderV1.CollateralConfig memory collateralConfig = oldConfig.collateralConfigs(i); config.setCollateralConfig( collateralConfig.collateralType, collateralConfig.debtLimit, collateralConfig.minCollateralRatio, collateralConfig.minCollateralRatio, collateralConfig.borrowRate, collateralConfig.originationFee, LIQUIDATION_BONUS, 0 ); priceFeed.setAssetOracle( collateralConfig.collateralType, address(oldPriceFeed.assetOracles(collateralConfig.collateralType)) ); } coreState.syncStateFromV1(oldCore); core.acceptUpgrade(payable(address(oldCore))); core.setDebtNotifier(debtNotifier); debtNotifier.a().setDebtNotifier(debtNotifier); address[] memory payees = new address[](2); payees[0] = bpool; payees[1] = address(core); uint256[] memory shares = new uint256[](2); shares[0] = uint256(90); shares[1] = uint256(10); feeDistributor.changePayees(payees, shares); a.controller().revokeRole(MANAGER_ROLE, address(this)); a.controller().revokeRole(DEFAULT_ADMIN_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import './IAddressProviderV1.sol'; interface IFeeDistributorV1 { event PayeeAdded(address indexed account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); function release() external; function changePayees(address[] memory _payees, uint256[] memory _shares) external; function a() external view returns (IAddressProviderV1); function lastReleasedAt() external view returns (uint256); function getPayees() external view returns (address[] memory); function totalShares() external view returns (uint256); function shares(address payee) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../liquidityMining/interfaces/IMIMO.sol"; import "../liquidityMining/interfaces/IMIMODistributor.sol"; import "../liquidityMining/interfaces/ISupplyMiner.sol"; import "../liquidityMining/interfaces/IDemandMiner.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "../governance/interfaces/IVotingEscrow.sol"; import "../interfaces/IAddressProvider.sol"; contract MIMODeployment { IGovernanceAddressProvider public ga; IMIMO public mimo; IMIMODistributor public mimoDistributor; ISupplyMiner public wethSupplyMiner; ISupplyMiner public wbtcSupplyMiner; ISupplyMiner public usdcSupplyMiner; IDemandMiner public demandMiner; IDebtNotifier public debtNotifier; IVotingEscrow public votingEscrow; address public weth; address public wbtc; address public usdc; modifier onlyManager() { require(ga.controller().hasRole(ga.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor( IGovernanceAddressProvider _ga, IMIMO _mimo, IMIMODistributor _mimoDistributor, ISupplyMiner _wethSupplyMiner, ISupplyMiner _wbtcSupplyMiner, ISupplyMiner _usdcSupplyMiner, IDemandMiner _demandMiner, IDebtNotifier _debtNotifier, IVotingEscrow _votingEscrow, address _weth, address _wbtc, address _usdc ) public { require(address(_ga) != address(0)); require(address(_mimo) != address(0)); require(address(_mimoDistributor) != address(0)); require(address(_wethSupplyMiner) != address(0)); require(address(_wbtcSupplyMiner) != address(0)); require(address(_usdcSupplyMiner) != address(0)); require(address(_demandMiner) != address(0)); require(address(_debtNotifier) != address(0)); require(address(_votingEscrow) != address(0)); require(_weth != address(0)); require(_wbtc != address(0)); require(_usdc != address(0)); ga = _ga; mimo = _mimo; mimoDistributor = _mimoDistributor; wethSupplyMiner = _wethSupplyMiner; wbtcSupplyMiner = _wbtcSupplyMiner; usdcSupplyMiner = _usdcSupplyMiner; demandMiner = _demandMiner; debtNotifier = _debtNotifier; votingEscrow = _votingEscrow; weth = _weth; wbtc = _wbtc; usdc = _usdc; } function setup() public onlyManager { //IAddressProvider parallel = a.parallel(); //bytes32 MIMO_MINTER_ROLE = keccak256("MIMO_MINTER_ROLE"); //bytes32 DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000; ga.setMIMO(mimo); ga.setVotingEscrow(votingEscrow); debtNotifier.setCollateralSupplyMiner(weth, wethSupplyMiner); debtNotifier.setCollateralSupplyMiner(wbtc, wbtcSupplyMiner); debtNotifier.setCollateralSupplyMiner(usdc, usdcSupplyMiner); address[] memory payees = new address[](4); payees[0] = address(wethSupplyMiner); payees[1] = address(wbtcSupplyMiner); payees[2] = address(usdcSupplyMiner); payees[3] = address(demandMiner); uint256[] memory shares = new uint256[](4); shares[0] = uint256(20); shares[1] = uint256(25); shares[2] = uint256(5); shares[3] = uint256(50); mimoDistributor.changePayees(payees, shares); bytes32 MANAGER_ROLE = ga.controller().MANAGER_ROLE(); ga.controller().renounceRole(MANAGER_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; import './IBaseDistributor.sol'; interface IMIMODistributorExtension { function startTime() external view returns (uint256); function currentIssuance() external view returns (uint256); function weeklyIssuanceAt(uint256 timestamp) external view returns (uint256); function totalSupplyAt(uint256 timestamp) external view returns (uint256); } interface IMIMODistributor is IBaseDistributor, IMIMODistributorExtension {} // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IDemandMiner { function deposit(uint256 amount) external; function withdraw(uint256 amount) external; function token() external view returns (IERC20); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '../../governance/interfaces/IGovernanceAddressProvider.sol'; interface IBaseDistributor { event PayeeAdded(address account, uint256 shares); event TokensReleased(uint256 newTokens, uint256 releasedAt); /** Public function to release the accumulated new MIMO tokens to the payees. @dev anyone can call this. */ function release() external; /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) external; function totalShares() external view returns (uint256); function shares(address) external view returns (uint256); function a() external view returns (IGovernanceAddressProvider); function mintableTokens() external view returns (uint256); /** Get current configured payees. @return array of current payees. */ function getPayees() external view returns (address[] memory); } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsDataProvider.sol"; import "../interfaces/IVaultsCore.sol"; contract RepayVault { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public constant REPAY_PER_VAULT = 10 ether; IAddressProvider public a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } function repay() public onlyManager { IVaultsCore core = a.core(); IVaultsDataProvider vaultsData = a.vaultsData(); uint256 vaultCount = a.vaultsData().vaultCount(); for (uint256 vaultId = 1; vaultId <= vaultCount; vaultId++) { uint256 baseDebt = vaultsData.vaultBaseDebt(vaultId); //if (vaultId==28 || vaultId==29 || vaultId==30 || vaultId==31 || vaultId==32 || vaultId==33 || vaultId==35){ // continue; //} if (baseDebt == 0) { continue; } core.repay(vaultId, REPAY_PER_VAULT); } IERC20 par = IERC20(a.stablex()); par.safeTransfer(msg.sender, par.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IWETH.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; contract VaultsCore is IVaultsCore, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; uint256 internal constant _MAX_INT = 2**256 - 1; IAddressProvider public override a; IWETH public override WETH; IVaultsCoreState public override state; IDebtNotifier public override debtNotifier; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } modifier onlyVaultOwner(uint256 _vaultId) { require(a.vaultsData().vaultOwner(_vaultId) == msg.sender); _; } constructor( IAddressProvider _addresses, IWETH _IWETH, IVaultsCoreState _vaultsCoreState ) public { require(address(_addresses) != address(0)); require(address(_IWETH) != address(0)); require(address(_vaultsCoreState) != address(0)); a = _addresses; WETH = _IWETH; state = _vaultsCoreState; } // For a contract to receive ETH, it needs to have a payable fallback function // https://ethereum.stackexchange.com/a/47415 receive() external payable { require(msg.sender == address(WETH)); } /* Allow smooth upgrading of the vaultscore. @dev this function approves token transfers to the new vaultscore of both stablex and all configured collateral types @param _newVaultsCore address of the new vaultscore */ function upgrade(address payable _newVaultsCore) public override onlyManager { require(address(_newVaultsCore) != address(0)); require(a.stablex().approve(_newVaultsCore, _MAX_INT)); for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; IERC20 asset = IERC20(collateralType); asset.safeApprove(_newVaultsCore, _MAX_INT); } } /* Allow smooth upgrading of the VaultsCore. @dev this function transfers both PAR and all configured collateral types to the new vaultscore. */ function acceptUpgrade(address payable _oldVaultsCore) public override onlyManager { IERC20 stableX = IERC20(a.stablex()); stableX.safeTransferFrom(_oldVaultsCore, address(this), stableX.balanceOf(_oldVaultsCore)); for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; IERC20 asset = IERC20(collateralType); asset.safeTransferFrom(_oldVaultsCore, address(this), asset.balanceOf(_oldVaultsCore)); } } /** Configure the debt notifier. @param _debtNotifier the new DebtNotifier module address. **/ function setDebtNotifier(IDebtNotifier _debtNotifier) public override onlyManager { require(address(_debtNotifier) != address(0)); debtNotifier = _debtNotifier; } /** Deposit an ERC20 token into the vault of the msg.sender as collateral @dev A new vault is created if no vault exists for the `msg.sender` with the specified collateral type. this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _collateralType the address of the collateral type to be deposited @param _amount the amount of tokens to be deposited in WEI. **/ function deposit(address _collateralType, uint256 _amount) public override { require(a.config().collateralIds(_collateralType) != 0); IERC20 asset = IERC20(_collateralType); asset.safeTransferFrom(msg.sender, address(this), _amount); _addCollateralToVault(_collateralType, _amount); } /** Wraps ETH and deposits WETH into the vault of the msg.sender as collateral @dev A new vault is created if no WETH vault exists **/ function depositETH() public payable override { WETH.deposit{ value: msg.value }(); _addCollateralToVault(address(WETH), msg.value); } /** Deposit an ERC20 token into the specified vault as collateral @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _vaultId the address of the collateral type to be deposited @param _amount the amount of tokens to be deposited in WEI. **/ function depositByVaultId(uint256 _vaultId, uint256 _amount) public override { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(v.collateralType != address(0)); IERC20 asset = IERC20(v.collateralType); asset.safeTransferFrom(msg.sender, address(this), _amount); _addCollateralToVaultById(_vaultId, _amount); } /** Wraps ETH and deposits WETH into the specified vault as collateral @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param _vaultId the address of the collateral type to be deposited **/ function depositETHByVaultId(uint256 _vaultId) public payable override { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(v.collateralType == address(WETH)); WETH.deposit{ value: msg.value }(); _addCollateralToVaultById(_vaultId, msg.value); } /** Deposit an ERC20 token into the vault of the msg.sender as collateral and borrows the specified amount of tokens in WEI @dev see deposit() and borrow() @param _collateralType the address of the collateral type to be deposited @param _depositAmount the amount of tokens to be deposited in WEI. @param _borrowAmount the amount of borrowed StableX tokens in WEI. **/ function depositAndBorrow( address _collateralType, uint256 _depositAmount, uint256 _borrowAmount ) public override { deposit(_collateralType, _depositAmount); uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender); borrow(vaultId, _borrowAmount); } /** Wraps ETH and deposits WETH into the vault of the msg.sender as collateral and borrows the specified amount of tokens in WEI @dev see depositETH() and borrow() @param _borrowAmount the amount of borrowed StableX tokens in WEI. **/ function depositETHAndBorrow(uint256 _borrowAmount) public payable override { depositETH(); uint256 vaultId = a.vaultsData().vaultId(address(WETH), msg.sender); borrow(vaultId, _borrowAmount); } function _addCollateralToVault(address _collateralType, uint256 _amount) internal { uint256 vaultId = a.vaultsData().vaultId(_collateralType, msg.sender); if (vaultId == 0) { vaultId = a.vaultsData().createVault(_collateralType, msg.sender); } _addCollateralToVaultById(vaultId, _amount); } function _addCollateralToVaultById(uint256 _vaultId, uint256 _amount) internal { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.add(_amount)); emit Deposited(_vaultId, _amount, msg.sender); } /** Withdraws ERC20 tokens from a vault. @dev Only the owner of a vault can withdraw collateral from it. `withdraw()` will fail if it would bring the vault below the minimum collateralization treshold. @param _vaultId the ID of the vault from which to withdraw the collateral. @param _amount the amount of ERC20 tokens to be withdrawn in WEI. **/ function withdraw(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { _removeCollateralFromVault(_vaultId, _amount); IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, _amount); } /** Withdraws ETH from a WETH vault. @dev Only the owner of a vault can withdraw collateral from it. `withdraw()` will fail if it would bring the vault below the minimum collateralization treshold. @param _vaultId the ID of the vault from which to withdraw the collateral. @param _amount the amount of ETH to be withdrawn in WEI. **/ function withdrawETH(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { _removeCollateralFromVault(_vaultId, _amount); IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(v.collateralType == address(WETH)); WETH.withdraw(_amount); msg.sender.transfer(_amount); } function _removeCollateralFromVault(uint256 _vaultId, uint256 _amount) internal { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); require(_amount <= v.collateralBalance); uint256 newCollateralBalance = v.collateralBalance.sub(_amount); a.vaultsData().setCollateralBalance(_vaultId, newCollateralBalance); if (v.baseDebt > 0) { // Save gas cost when withdrawing from 0 debt vault state.refreshCollateral(v.collateralType); uint256 newCollateralValue = a.priceFeed().convertFrom(v.collateralType, newCollateralBalance); require( a.liquidationManager().isHealthy( newCollateralValue, a.vaultsData().vaultDebt(_vaultId), a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).minCollateralRatio ) ); } emit Withdrawn(_vaultId, _amount, msg.sender); } /** Borrow new PAR tokens from a vault. @dev Only the owner of a vault can borrow from it. `borrow()` will update the outstanding vault debt to the current time before attempting the withdrawal. `borrow()` will fail if it would bring the vault below the minimum collateralization treshold. @param _vaultId the ID of the vault from which to borrow. @param _amount the amount of borrowed PAR tokens in WEI. **/ function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); // Make sure current rate is up to date state.refreshCollateral(v.collateralType); uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType); uint256 newDebt = _amount; if (originationFeePercentage > 0) { newDebt = newDebt.add(_amount.wadMul(originationFeePercentage)); } // Increment vault borrow balance uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(newDebt, cumulativeRates(v.collateralType)); a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt)); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId); require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType)); bool isHealthy = a.liquidationManager().isHealthy( collateralValue, newVaultDebt, a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).minCollateralRatio ); require(isHealthy); a.stablex().mint(msg.sender, _amount); debtNotifier.debtChanged(_vaultId); emit Borrowed(_vaultId, _amount, msg.sender); } /** Convenience function to repay all debt of a vault @dev `repayAll()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the debt. **/ function repayAll(uint256 _vaultId) public override { repay(_vaultId, _MAX_INT); } /** Repay an outstanding PAR balance to a vault. @dev `repay()` will update the outstanding vault debt to the current time. @param _vaultId the ID of the vault for which to repay the outstanding debt balance. @param _amount the amount of PAR tokens in WEI to be repaid. **/ function repay(uint256 _vaultId, uint256 _amount) public override nonReentrant { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); // Make sure current rate is up to date state.refreshCollateral(collateralType); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); // Decrement vault borrow balance if (_amount >= currentVaultDebt) { //full repayment _amount = currentVaultDebt; //only pay back what's outstanding } _reduceVaultDebt(_vaultId, _amount); a.stablex().burn(msg.sender, _amount); debtNotifier.debtChanged(_vaultId); emit Repaid(_vaultId, _amount, msg.sender); } /** Internal helper function to reduce the debt of a vault. @dev assumes cumulative rates for the vault's collateral type are up to date. please call `refreshCollateral()` before calling this function. @param _vaultId the ID of the vault for which to reduce the debt. @param _amount the amount of debt to be reduced. **/ function _reduceVaultDebt(uint256 _vaultId, uint256 _amount) internal { address collateralType = a.vaultsData().vaultCollateralType(_vaultId); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); uint256 remainder = currentVaultDebt.sub(_amount); uint256 cumulativeRate = cumulativeRates(collateralType); if (remainder == 0) { a.vaultsData().setBaseDebt(_vaultId, 0); } else { uint256 newBaseDebt = a.ratesManager().calculateBaseDebt(remainder, cumulativeRate); a.vaultsData().setBaseDebt(_vaultId, newBaseDebt); } } /** Liquidate a vault that is below the liquidation treshold by repaying its outstanding debt. @dev `liquidate()` will update the outstanding vault debt to the current time and pay a `liquidationBonus` to the liquidator. `liquidate()` can be called by anyone. @param _vaultId the ID of the vault to be liquidated. **/ function liquidate(uint256 _vaultId) public override { liquidatePartial(_vaultId, _MAX_INT); } /** Liquidate a vault partially that is below the liquidation treshold by repaying part of its outstanding debt. @dev `liquidatePartial()` will update the outstanding vault debt to the current time and pay a `liquidationBonus` to the liquidator. A LiquidationFee will be applied to the borrower during the liquidation. This means that the change in outstanding debt can be smaller than the repaid amount. `liquidatePartial()` can be called by anyone. @param _vaultId the ID of the vault to be liquidated. @param _amount the amount of debt+liquidationFee to repay. **/ function liquidatePartial(uint256 _vaultId, uint256 _amount) public override nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); state.refreshCollateral(v.collateralType); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 currentVaultDebt = a.vaultsData().vaultDebt(_vaultId); require( !a.liquidationManager().isHealthy( collateralValue, currentVaultDebt, a.config().collateralConfigs(a.config().collateralIds(v.collateralType)).liquidationRatio ) ); uint256 repaymentAfterLiquidationFeeRatio = WadRayMath.wad().sub( a.config().collateralLiquidationFee(v.collateralType) ); uint256 maxLiquiditionCost = currentVaultDebt.wadDiv(repaymentAfterLiquidationFeeRatio); uint256 repayAmount; if (_amount > maxLiquiditionCost) { _amount = maxLiquiditionCost; repayAmount = currentVaultDebt; } else { repayAmount = _amount.wadMul(repaymentAfterLiquidationFeeRatio); } // collateral value to be received by the liquidator is based on the total amount repaid (including the liquidationFee). uint256 collateralValueToReceive = _amount.add(a.liquidationManager().liquidationBonus(v.collateralType, _amount)); uint256 insuranceAmount = 0; if (collateralValueToReceive >= collateralValue) { // Not enough collateral for debt & liquidation fee collateralValueToReceive = collateralValue; uint256 discountedCollateralValue = a.liquidationManager().applyLiquidationDiscount( v.collateralType, collateralValue ); if (currentVaultDebt > discountedCollateralValue) { // Not enough collateral for debt alone insuranceAmount = currentVaultDebt.sub(discountedCollateralValue); require(a.stablex().balanceOf(address(this)) >= insuranceAmount); a.stablex().burn(address(this), insuranceAmount); // Insurance uses local reserves to pay down debt emit InsurancePaid(_vaultId, insuranceAmount, msg.sender); } repayAmount = currentVaultDebt.sub(insuranceAmount); _amount = discountedCollateralValue; } // reduce the vault debt by repayAmount _reduceVaultDebt(_vaultId, repayAmount.add(insuranceAmount)); a.stablex().burn(msg.sender, _amount); // send the claimed collateral to the liquidator uint256 collateralToReceive = a.priceFeed().convertTo(v.collateralType, collateralValueToReceive); a.vaultsData().setCollateralBalance(_vaultId, v.collateralBalance.sub(collateralToReceive)); IERC20 asset = IERC20(v.collateralType); asset.safeTransfer(msg.sender, collateralToReceive); debtNotifier.debtChanged(_vaultId); emit Liquidated(_vaultId, repayAmount, collateralToReceive, v.owner, msg.sender); } /** Returns the cumulativeRate of a collateral type. This function exists for backwards compatibility with the VaultsDataProvider. @param _collateralType the address of the collateral type. **/ function cumulativeRates(address _collateralType) public view override returns (uint256) { return state.cumulativeRates(_collateralType); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCoreState.sol"; import "../v1/interfaces/IVaultsCoreV1.sol"; contract VaultsCoreState is IVaultsCoreState { using SafeMath for uint256; using WadRayMath for uint256; uint256 internal constant _MAX_INT = 2**256 - 1; bool public override synced = false; IAddressProvider public override a; mapping(address => uint256) public override cumulativeRates; mapping(address => uint256) public override lastRefresh; modifier onlyConfig() { require(msg.sender == address(a.config())); _; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } modifier notSynced() { require(!synced); _; } constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Calculate the available income @return available income that has not been minted yet. **/ function availableIncome() public view override returns (uint256) { return a.vaultsData().debt().sub(a.stablex().totalSupply()); } /** Refresh the cumulative rates and debts of all vaults and all collateral types. @dev anyone can call this. **/ function refresh() public override { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; refreshCollateral(collateralType); } } /** Sync state with another instance. This is used during version upgrade to keep V2 in sync with V2. @dev This call will read the state via `cumulativeRates(address collateralType)` and `lastRefresh(address collateralType)`. @param _stateAddress address from which the state is to be copied. **/ function syncState(IVaultsCoreState _stateAddress) public override onlyManager notSynced { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; cumulativeRates[collateralType] = _stateAddress.cumulativeRates(collateralType); lastRefresh[collateralType] = _stateAddress.lastRefresh(collateralType); } synced = true; } /** Sync state with v1 core. This is used during version upgrade to keep V2 in sync with V1. @dev This call will read the state via `cumulativeRates(address collateralType)` and `lastRefresh(address collateralType)`. @param _core address of core v1 from which the state is to be copied. **/ function syncStateFromV1(IVaultsCoreV1 _core) public override onlyManager notSynced { for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; cumulativeRates[collateralType] = _core.cumulativeRates(collateralType); lastRefresh[collateralType] = _core.lastRefresh(collateralType); } synced = true; } /** Initialize the cumulative rates to 1 for a new collateral type. @param _collateralType the address of the new collateral type to be initialized **/ function initializeRates(address _collateralType) public override onlyConfig { require(_collateralType != address(0)); lastRefresh[_collateralType] = block.timestamp; cumulativeRates[_collateralType] = WadRayMath.ray(); } /** Refresh the cumulative rate of a collateraltype. @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be refreshed. **/ function refreshCollateral(address _collateralType) public override { require(_collateralType != address(0)); require(a.config().collateralIds(_collateralType) != 0); uint256 timestamp = block.timestamp; uint256 timeElapsed = timestamp.sub(lastRefresh[_collateralType]); _refreshCumulativeRate(_collateralType, timeElapsed); lastRefresh[_collateralType] = timestamp; } /** Internal function to increase the cumulative rate over a specified time period @dev this updates the debt for all vaults with the specified collateral type. @param _collateralType the address of the collateral type to be updated @param _timeElapsed the amount of time in seconds to add to the cumulative rate **/ function _refreshCumulativeRate(address _collateralType, uint256 _timeElapsed) internal { uint256 borrowRate = a.config().collateralBorrowRate(_collateralType); uint256 oldCumulativeRate = cumulativeRates[_collateralType]; cumulativeRates[_collateralType] = a.ratesManager().calculateCumulativeRate( borrowRate, oldCumulativeRate, _timeElapsed ); emit CumulativeRateUpdated(_collateralType, _timeElapsed, cumulativeRates[_collateralType]); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/ISTABLEX.sol"; import "./interfaces/IFeeDistributorV1.sol"; import "./interfaces/IAddressProviderV1.sol"; contract FeeDistributorV1 is IFeeDistributorV1, ReentrancyGuard { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); uint256 public override lastReleasedAt; IAddressProviderV1 public override a; uint256 public override totalShares; mapping(address => uint256) public override shares; address[] public payees; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor(IAddressProviderV1 _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Public function to release the accumulated fee income to the payees. @dev anyone can call this. */ function release() public override nonReentrant { uint256 income = a.core().availableIncome(); require(income > 0, "income is 0"); require(payees.length > 0, "Payees not configured yet"); lastReleasedAt = now; // Mint USDX to all receivers for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(income, payee); } emit FeeReleased(income, lastReleasedAt); } /** Get current configured payees. @return array of current payees. */ function getPayees() public view override returns (address[] memory) { return payees; } /** Internal function to release a percentage of income to a specific payee @dev uses totalShares to calculate correct share @param _totalIncomeReceived Total income for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalIncomeReceived, address _payee) internal { uint256 payment = _totalIncomeReceived.mul(shares[_payee]).div(totalShares); a.stablex().mint(_payee, payment); } /** Internal function to add a new payee. @dev will update totalShares and therefore reduce the relative share of all other payees. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0), "payee is the zero address"); require(_shares > 0, "shares are 0"); require(shares[_payee] == 0, "payee already has shares"); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); emit PayeeAdded(_payee, _shares); } /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager { require(_payees.length == _shares.length, "Payees and shares mismatched"); require(_payees.length > 0, "No payees"); uint256 income = a.core().availableIncome(); if (income > 0 && payees.length > 0) { release(); } for (uint256 i = 0; i < payees.length; i++) { delete shares[payees[i]]; } delete payees; totalShares = 0; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } } // solium-disable security/no-block-members // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/ISTABLEX.sol"; /** * @title USDX * @notice Stablecoin which can be minted against collateral in a vault */ contract USDX is ISTABLEX, ERC20("USD Stablecoin", "USDX") { IAddressProvider public override a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } function mint(address account, uint256 amount) public override onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) public override onlyMinter { _burn(account, amount); } modifier onlyMinter() { require(a.controller().hasRole(a.controller().MINTER_ROLE(), msg.sender), "Caller is not a minter"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // solium-disable security/no-block-members // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IAddressProvider.sol"; import "../interfaces/ISTABLEX.sol"; /** * @title PAR * @notice Stablecoin which can be minted against collateral in a vault */ contract PAR is ISTABLEX, ERC20("PAR Stablecoin", "PAR") { IAddressProvider public override a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } function mint(address account, uint256 amount) public override onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) public override onlyMinter { _burn(account, amount); } modifier onlyMinter() { require(a.controller().hasRole(a.controller().MINTER_ROLE(), msg.sender), "Caller is not a minter"); _; } } // solium-disable security/no-block-members // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; /** * @title MIMO * @notice MIMO Governance token */ contract MIMO is ERC20("MIMO Parallel Governance Token", "MIMO") { IGovernanceAddressProvider public a; bytes32 public constant MIMO_MINTER_ROLE = keccak256("MIMO_MINTER_ROLE"); constructor(IGovernanceAddressProvider _a) public { require(address(_a) != address(0)); a = _a; } modifier onlyMIMOMinter() { require(a.controller().hasRole(MIMO_MINTER_ROLE, msg.sender), "Caller is not MIMO Minter"); _; } function mint(address account, uint256 amount) public onlyMIMOMinter { _mint(account, amount); } function burn(address account, uint256 amount) public onlyMIMOMinter { _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../token/MIMO.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "../liquidityMining/interfaces/IMIMODistributor.sol"; contract PreUseAirdrop { using SafeERC20 for IERC20; struct Payout { address recipient; uint256 amount; } Payout[] public payouts; IGovernanceAddressProvider public ga; IMIMODistributor public mimoDistributor; modifier onlyManager() { require(ga.controller().hasRole(ga.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } constructor(IGovernanceAddressProvider _ga, IMIMODistributor _mimoDistributor) public { require(address(_ga) != address(0)); require(address(_mimoDistributor) != address(0)); ga = _ga; mimoDistributor = _mimoDistributor; payouts.push(Payout(0xBBd92c75C6f8B0FFe9e5BCb2e56a5e2600871a10, 271147720731494841509243076)); payouts.push(Payout(0xcc8793d5eB95fAa707ea4155e09b2D3F44F33D1E, 210989402066696530434956148)); payouts.push(Payout(0x185f19B43d818E10a31BE68f445ef8EDCB8AFB83, 22182938994846641176273320)); payouts.push(Payout(0xDeD9F901D40A96C3Ee558E6885bcc7eFC51ad078, 13678603288816593264718593)); payouts.push(Payout(0x0B3890bbF2553Bd098B45006aDD734d6Fbd6089E, 8416873402881706143143730)); payouts.push(Payout(0x3F41a1CFd3C8B8d9c162dE0f42307a0095A6e5DF, 7159719590701445955473554)); payouts.push(Payout(0x9115BaDce4873d58fa73b08279529A796550999a, 5632453715407980754075398)); payouts.push(Payout(0x7BC8C0B66d7f0E2193ED11eeCAAfE7c1837b926f, 5414893264683531027764823)); payouts.push(Payout(0xE7809aaaaa78E5a24E059889E561f598F3a4664c, 4712320945661497844704387)); payouts.push(Payout(0xf4D3566729f257edD0D4bF365d8f0Db7bF56e1C6, 2997276841876706895655431)); payouts.push(Payout(0x6Cf9AA65EBaD7028536E353393630e2340ca6049, 2734992792750385321760387)); payouts.push(Payout(0x74386381Cb384CC0FBa0Ac669d22f515FfC147D2, 1366427847282177615773594)); payouts.push(Payout(0x9144b150f28437E06Ab5FF5190365294eb1E87ec, 1363226310703652991601514)); payouts.push(Payout(0x5691d53685e8e219329bD8ADf62b1A0A17df9D11, 702790464733701088417744)); payouts.push(Payout(0x2B91B4f5223a0a1f5c7e1D139dDdD6B5B57C7A51, 678663683269882192090830)); payouts.push(Payout(0x8ddBad507F3b20239516810C308Ba4f3BaeAf3a1, 635520835923336863138335)); payouts.push(Payout(0xc3874A2C59b9779A75874Be6B5f0b578120A8701, 488385391000796390198744)); payouts.push(Payout(0x0A22C160f7E57F2e7d88b2fa1B1B03571bdE6128, 297735186117080365383063)); payouts.push(Payout(0x0a1aa2b65832fC0c71f2Ba488c84BeE0b9DB9692, 132688033756581498940995)); payouts.push(Payout(0xAf7b7AbC272a3aE6dD6dA41b9832C758477a85f2, 130254714680714068405131)); payouts.push(Payout(0xCDb17d9bCbA8E3bab6F68D59065efe784700Bee1, 71018627162763037055295)); payouts.push(Payout(0x4Dec19003F9Bb01A4c0D089605618b2d76deE30d, 69655357581389001902516)); payouts.push(Payout(0x31AacA1940C82130c2D4407E609e626E87A7BC18, 21678478730854029506989)); payouts.push(Payout(0xBc77AB8dd8BAa6ddf0D0c241d31b2e30bcEC127d, 21573657481017931484432)); payouts.push(Payout(0x1c25cDD83Cd7106C3dcB361230eC9E6930Aadd30, 14188368728356337446426)); payouts.push(Payout(0xf1B78ed53fa2f9B8cFfa677Ad8023aCa92109d08, 13831474058511281838532)); payouts.push(Payout(0xd27962455de27561e62345a516931F2392997263, 6968208393315527988941)); payouts.push(Payout(0xD8A4411C623aD361E98bC9D98cA33eE1cF308Bca, 4476771187861728227997)); payouts.push(Payout(0x1f06fA59809ee23Ee06e533D67D29C6564fC1964, 3358338614042115121460)); payouts.push(Payout(0xeDccc1501e3BCC8b3973B9BE33f6Bd7072d28388, 2328788070517256560738)); payouts.push(Payout(0xD738A884B2aFE625d372260E57e86E3eB4d5e1D7, 466769668474372743140)); payouts.push(Payout(0x6942b1b6526Fa05035d47c09B419039c00Ef7545, 442736084997163005698)); } function airdrop() public onlyManager { MIMO mimo = MIMO(address(ga.mimo())); for (uint256 i = 0; i < payouts.length; i++) { Payout memory payout = payouts[i]; mimo.mint(payout.recipient, payout.amount); } require(mimoDistributor.mintableTokens() > 0); bytes32 MIMO_MINTER_ROLE = mimo.MIMO_MINTER_ROLE(); ga.controller().renounceRole(MIMO_MINTER_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IMIMODistributor.sol"; import "./BaseDistributor.sol"; contract MIMODistributorV2 is BaseDistributor, IMIMODistributorExtension { using SafeMath for uint256; using WadRayMath for uint256; uint256 private constant _SECONDS_PER_YEAR = 365 days; uint256 private constant _SECONDS_PER_WEEK = 7 days; uint256 private constant _WEEKLY_R = 986125e21; // -1.3875% per week (-5.55% / 4) uint256 private _FIRST_WEEK_TOKENS; uint256 public override startTime; uint256 public alreadyMinted; constructor( IGovernanceAddressProvider _a, uint256 _startTime, IMIMODistributor _mimoDistributor ) public { require(address(_a) != address(0)); require(address(_mimoDistributor) != address(0)); a = _a; startTime = _startTime; alreadyMinted = _mimoDistributor.totalSupplyAt(startTime); uint256 weeklyIssuanceV1 = _mimoDistributor.weeklyIssuanceAt(startTime); _FIRST_WEEK_TOKENS = weeklyIssuanceV1 / 4; // reduce weeky issuance by 4 } /** Get current monthly issuance of new MIMO tokens. @return number of monthly issued tokens currently`. */ function currentIssuance() public view override returns (uint256) { return weeklyIssuanceAt(now); } /** Get monthly issuance of new MIMO tokens at `timestamp`. @dev invalid for timestamps before deployment @param timestamp for which to calculate the monthly issuance @return number of monthly issued tokens at `timestamp`. */ function weeklyIssuanceAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); return _WEEKLY_R.rayPow(elapsedWeeks).rayMul(_FIRST_WEEK_TOKENS); } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return totalSupplyAt(now).sub(a.mimo().totalSupply()); } /** Calculates the totalSupply for any point after `startTime` @param timestamp for which to calculate the totalSupply @return totalSupply at timestamp. */ function totalSupplyAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); uint256 lastWeekSeconds = elapsedSeconds % _SECONDS_PER_WEEK; uint256 one = WadRayMath.ray(); uint256 fullWeeks = one.sub(_WEEKLY_R.rayPow(elapsedWeeks)).rayMul(_FIRST_WEEK_TOKENS).rayDiv(one.sub(_WEEKLY_R)); uint256 currentWeekIssuance = weeklyIssuanceAt(timestamp); uint256 partialWeek = currentWeekIssuance.mul(lastWeekSeconds).div(_SECONDS_PER_WEEK); return alreadyMinted.add(fullWeeks.add(partialWeek)); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); a.mimo().mint(_payee, payment); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IBaseDistributor.sol"; /* Distribution Formula: 55.5m MIMO in first week -5.55% redution per week total(timestamp) = _SECONDS_PER_WEEK * ( (1-weeklyR^(timestamp/_SECONDS_PER_WEEK)) / (1-weeklyR) ) + timestamp % _SECONDS_PER_WEEK * (1-weeklyR^(timestamp/_SECONDS_PER_WEEK) */ abstract contract BaseDistributor is IBaseDistributor { using SafeMath for uint256; using WadRayMath for uint256; uint256 public override totalShares; mapping(address => uint256) public override shares; address[] public payees; IGovernanceAddressProvider public override a; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } /** Public function to release the accumulated new MIMO tokens to the payees. @dev anyone can call this. */ function release() public override { uint256 newTokens = mintableTokens(); require(newTokens > 0, "newTokens is 0"); require(payees.length > 0, "Payees not configured yet"); // Mint MIMO to all receivers for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(newTokens, payee); } emit TokensReleased(newTokens, now); } /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager { require(_payees.length == _shares.length, "Payees and shares mismatched"); require(_payees.length > 0, "No payees"); if (payees.length > 0 && mintableTokens() > 0) { release(); } for (uint256 i = 0; i < payees.length; i++) { delete shares[payees[i]]; } delete payees; totalShares = 0; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** Get current configured payees. @return array of current payees. */ function getPayees() public view override returns (address[] memory) { return payees; } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view virtual override returns (uint256); /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal virtual; /** Internal function to add a new payee. @dev will update totalShares and therefore reduce the relative share of all other payees. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0), "payee is the zero address"); require(_shares > 0, "shares are 0"); require(shares[_payee] == 0, "payee already has shares"); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); emit PayeeAdded(_payee, _shares); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/interfaces/IRootChainManager.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./BaseDistributor.sol"; contract PolygonDistributor is BaseDistributor { using SafeMath for uint256; IRootChainManager public rootChainManager; address public erc20Predicate; constructor( IGovernanceAddressProvider _a, IRootChainManager _rootChainManager, address _erc20Predicate ) public { require(address(_a) != address(0)); require(address(_rootChainManager) != address(0)); require(_erc20Predicate != address(0)); a = _a; rootChainManager = _rootChainManager; erc20Predicate = _erc20Predicate; } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return a.mimo().balanceOf(address(this)); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); a.mimo().approve(erc20Predicate, payment); rootChainManager.depositFor(_payee, address(a.mimo()), abi.encode(payment)); } } pragma solidity 0.6.12; interface IRootChainManager { event TokenMapped(address indexed rootToken, address indexed childToken, bytes32 indexed tokenType); event PredicateRegistered(bytes32 indexed tokenType, address indexed predicateAddress); function registerPredicate(bytes32 tokenType, address predicateAddress) external; function mapToken( address rootToken, address childToken, bytes32 tokenType ) external; function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../liquidityMining/GenericMiner.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; contract MockGenericMiner is GenericMiner { constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {} function increaseStake(address user, uint256 value) public { _increaseStake(user, value); } function decreaseStake(address user, uint256 value) public { _decreaseStake(user, value); } } //SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "./interfaces/IGenericMiner.sol"; /* GenericMiner is based on ERC2917. https://github.com/gnufoo/ERC2917-Proposal The Objective of GenericMiner is to implement a decentralized staking mechanism, which calculates _users' share by accumulating stake * time. And calculates _users revenue from anytime t0 to t1 by the formula below: user_accumulated_stake(time1) - user_accumulated_stake(time0) _____________________________________________________________________________ * (gross_stake(t1) - gross_stake(t0)) total_accumulated_stake(time1) - total_accumulated_stake(time0) */ contract GenericMiner is IGenericMiner { using SafeMath for uint256; using WadRayMath for uint256; mapping(address => UserInfo) internal _users; uint256 public override totalStake; IGovernanceAddressProvider public override a; uint256 internal _balanceTracker; uint256 internal _accAmountPerShare; constructor(IGovernanceAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Releases the outstanding MIMO balance to the user. @param _user the address of the user for which the MIMO tokens will be released. */ function releaseMIMO(address _user) public virtual override { UserInfo storage userInfo = _users[_user]; _refresh(); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; require(a.mimo().transfer(_user, pending)); } /** Returns the number of tokens a user has staked. @param _user the address of the user. @return number of staked tokens */ function stake(address _user) public view override returns (uint256) { return _users[_user].stake; } /** Returns the number of tokens a user can claim via `releaseMIMO`. @param _user the address of the user. @return number of MIMO tokens that the user can claim */ function pendingMIMO(address _user) public view override returns (uint256) { uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); uint256 accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); return _users[_user].stake.rayMul(accAmountPerShare.sub(_users[_user].accAmountPerShare)); } /** Returns the userInfo stored of a user. @param _user the address of the user. @return `struct UserInfo { uint256 stake; uint256 rewardDebt; }` **/ function userInfo(address _user) public view override returns (UserInfo memory) { return _users[_user]; } /** Refreshes the global state and subsequently decreases the stake a user has. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be reduced */ function _decreaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message _refresh(); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.stake = userInfo.stake.sub(value); userInfo.accAmountPerShare = _accAmountPerShare; totalStake = totalStake.sub(value); require(a.mimo().transfer(user, pending)); emit StakeDecreased(user, value); } /** Refreshes the global state and subsequently increases a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be increased */ function _increaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; _refresh(); uint256 pending; if (userInfo.stake > 0) { pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); } totalStake = totalStake.add(value); userInfo.stake = userInfo.stake.add(value); userInfo.accAmountPerShare = _accAmountPerShare; if (pending > 0) { require(a.mimo().transfer(user, pending)); } emit StakeIncreased(user, value); } /** Refreshes the global state and subsequently updates a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param stake the new amount of stake for the user */ function _updateStake(address user, uint256 stake) internal returns (bool) { uint256 oldStake = _users[user].stake; if (stake > oldStake) { _increaseStake(user, stake.sub(oldStake)); } if (stake < oldStake) { _decreaseStake(user, oldStake.sub(stake)); } } /** Internal read function to calculate the number of MIMO tokens that have accumulated since the last token release. @dev This is an internal call and meant to be called within derivative contracts. @return newly accumulated token balance */ function _newTokensReceived() internal view returns (uint256) { return a.mimo().balanceOf(address(this)).sub(_balanceTracker); } /** Updates the internal state variables after accounting for newly received MIMO tokens. */ function _refresh() internal { if (totalStake == 0) { return; } uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); _balanceTracker = currentBalance; _accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./GenericMiner.sol"; import "./interfaces/IVotingMiner.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "../governance/interfaces/IVotingEscrow.sol"; contract VotingMiner is IVotingMiner, GenericMiner { constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {} /** Releases the outstanding MIMO balance to the user. @param _user the address of the user for which the MIMO tokens will be released. */ function releaseMIMO(address _user) public override { IVotingEscrow votingEscrow = a.votingEscrow(); require((msg.sender == _user) || (msg.sender == address(votingEscrow))); UserInfo storage userInfo = _users[_user]; _refresh(); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; uint256 votingPower = votingEscrow.balanceOf(_user); totalStake = totalStake.add(votingPower).sub(userInfo.stake); userInfo.stake = votingPower; if (pending > 0) { require(a.mimo().transfer(_user, pending)); } } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; interface IVotingMiner {} // SPDX-License-Identifier: AGPL-3.0 /* solium-disable security/no-block-members */ pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IVotingEscrow.sol"; import "./interfaces/IGovernanceAddressProvider.sol"; import "../liquidityMining/interfaces/IGenericMiner.sol"; /** * @title VotingEscrow * @notice Lockup GOV, receive vGOV (voting weight that decays over time) * @dev Supports: * 1) Tracking MIMO Locked up * 2) Decaying voting weight lookup * 3) Closure of contract */ contract VotingEscrow is IVotingEscrow, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAXTIME = 1460 days; // 365 * 4 years uint256 public minimumLockTime = 1 days; bool public expired = false; IERC20 public override stakingToken; mapping(address => LockedBalance) public locked; string public override name; string public override symbol; // solhint-disable-next-line uint256 public constant override decimals = 18; // AddressProvider IGovernanceAddressProvider public a; IGenericMiner public miner; constructor( IERC20 _stakingToken, IGovernanceAddressProvider _a, IGenericMiner _miner, string memory _name, string memory _symbol ) public { require(address(_stakingToken) != address(0)); require(address(_a) != address(0)); require(address(_miner) != address(0)); stakingToken = _stakingToken; a = _a; miner = _miner; name = _name; symbol = _symbol; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** @dev Modifier to ensure contract has not yet expired */ modifier contractNotExpired() { require(!expired, "Contract is expired"); _; } /** * @dev Creates a new lock * @param _value Total units of StakingToken to lockup * @param _unlockTime Time at which the stake should unlock */ function createLock(uint256 _value, uint256 _unlockTime) external override nonReentrant contractNotExpired { LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end }); require(_value > 0, "Must stake non zero amount"); require(locked_.amount == 0, "Withdraw old tokens first"); require(_unlockTime > block.timestamp, "Can only lock until time in the future"); require(_unlockTime.sub(block.timestamp) > minimumLockTime, "Lock duration should be larger than minimum locktime"); _depositFor(msg.sender, _value, _unlockTime, locked_, LockAction.CREATE_LOCK); } /** * @dev Increases amount of stake thats locked up & resets decay * @param _value Additional units of StakingToken to add to exiting stake */ function increaseLockAmount(uint256 _value) external override nonReentrant contractNotExpired { LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end }); require(_value > 0, "Must stake non zero amount"); require(locked_.amount > 0, "No existing lock found"); require(locked_.end > block.timestamp, "Cannot add to expired lock. Withdraw"); _depositFor(msg.sender, _value, 0, locked_, LockAction.INCREASE_LOCK_AMOUNT); } /** * @dev Increases length of lockup & resets decay * @param _unlockTime New unlocktime for lockup */ function increaseLockLength(uint256 _unlockTime) external override nonReentrant contractNotExpired { LockedBalance memory locked_ = LockedBalance({ amount: locked[msg.sender].amount, end: locked[msg.sender].end }); require(locked_.amount > 0, "Nothing is locked"); require(locked_.end > block.timestamp, "Lock expired"); require(_unlockTime > locked_.end, "Can only increase lock time"); require(_unlockTime.sub(locked_.end) > minimumLockTime, "Lock duration should be larger than minimum locktime"); _depositFor(msg.sender, 0, _unlockTime, locked_, LockAction.INCREASE_LOCK_TIME); } /** * @dev Withdraws all the senders stake, providing lockup is over */ function withdraw() external override { _withdraw(msg.sender); } /** * @dev Ends the contract, unlocking all stakes. * No more staking can happen. Only withdraw. */ function expireContract() external override onlyManager contractNotExpired { expired = true; emit Expired(); } /** * @dev Set miner address. * @param _miner new miner contract address */ function setMiner(IGenericMiner _miner) external override onlyManager contractNotExpired { miner = _miner; } /** * @dev Set minimumLockTime. * @param _minimumLockTime minimum lockTime */ function setMinimumLockTime(uint256 _minimumLockTime) external override onlyManager contractNotExpired { minimumLockTime = _minimumLockTime; } /*************************************** GETTERS ****************************************/ /** * @dev Gets the user's votingWeight at the current time. * @param _owner User for which to return the votingWeight * @return uint256 Balance of user */ function balanceOf(address _owner) public view override returns (uint256) { return balanceOfAt(_owner, block.timestamp); } /** * @dev Gets a users votingWeight at a given block timestamp * @param _owner User for which to return the balance * @param _blockTime Timestamp for which to calculate balance. Can not be in the past * @return uint256 Balance of user */ function balanceOfAt(address _owner, uint256 _blockTime) public view override returns (uint256) { require(_blockTime >= block.timestamp, "Must pass block timestamp in the future"); LockedBalance memory currentLock = locked[_owner]; if (currentLock.end <= _blockTime) return 0; uint256 remainingLocktime = currentLock.end.sub(_blockTime); if (remainingLocktime > MAXTIME) { remainingLocktime = MAXTIME; } return currentLock.amount.mul(remainingLocktime).div(MAXTIME); } /** * @dev Deposits or creates a stake for a given address * @param _addr User address to assign the stake * @param _value Total units of StakingToken to lockup * @param _unlockTime Time at which the stake should unlock * @param _oldLocked Previous amount staked by this user * @param _action See LockAction enum */ function _depositFor( address _addr, uint256 _value, uint256 _unlockTime, LockedBalance memory _oldLocked, LockAction _action ) internal { LockedBalance memory newLocked = LockedBalance({ amount: _oldLocked.amount, end: _oldLocked.end }); // Adding to existing lock, or if a lock is expired - creating a new one newLocked.amount = newLocked.amount.add(_value); if (_unlockTime != 0) { newLocked.end = _unlockTime; } locked[_addr] = newLocked; if (_value != 0) { stakingToken.safeTransferFrom(_addr, address(this), _value); } miner.releaseMIMO(_addr); emit Deposit(_addr, _value, newLocked.end, _action, block.timestamp); } /** * @dev Withdraws a given users stake, providing the lockup has finished * @param _addr User for which to withdraw */ function _withdraw(address _addr) internal nonReentrant { LockedBalance memory oldLock = LockedBalance({ end: locked[_addr].end, amount: locked[_addr].amount }); require(block.timestamp >= oldLock.end || expired, "The lock didn't expire"); require(oldLock.amount > 0, "Must have something to withdraw"); uint256 value = uint256(oldLock.amount); LockedBalance memory currentLock = LockedBalance({ end: 0, amount: 0 }); locked[_addr] = currentLock; stakingToken.safeTransfer(_addr, value); miner.releaseMIMO(_addr); emit Withdraw(_addr, value, block.timestamp); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IMIMO.sol"; import "./interfaces/IGenericMiner.sol"; import "hardhat/console.sol"; contract PARMiner { using SafeMath for uint256; using WadRayMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 stake; uint256 accAmountPerShare; uint256 accParAmountPerShare; } event StakeIncreased(address indexed user, uint256 stake); event StakeDecreased(address indexed user, uint256 stake); IERC20 public par; mapping(address => UserInfo) internal _users; uint256 public totalStake; IGovernanceAddressProvider public a; uint256 internal _balanceTracker; uint256 internal _accAmountPerShare; uint256 internal _parBalanceTracker; uint256 internal _accParAmountPerShare; constructor(IGovernanceAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; par = IERC20(_addresses.parallel().stablex()); } /** Deposit an ERC20 pool token for staking @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param amount the amount of tokens to be deposited. Unit is in WEI. **/ function deposit(uint256 amount) public { par.safeTransferFrom(msg.sender, address(this), amount); _increaseStake(msg.sender, amount); } /** Withdraw staked ERC20 pool tokens. Will fail if user does not have enough tokens staked. @param amount the amount of tokens to be withdrawn. Unit is in WEI. **/ function withdraw(uint256 amount) public { par.safeTransfer(msg.sender, amount); _decreaseStake(msg.sender, amount); } /** Releases the outstanding MIMO balance to the user. @param _user the address of the user for which the MIMO tokens will be released. */ function releaseMIMO(address _user) public virtual { UserInfo storage userInfo = _users[_user]; _refresh(); _refreshPAR(totalStake); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; require(a.mimo().transfer(_user, pending)); } /** Releases the outstanding PAR reward balance to the user. @param _user the address of the user for which the PAR tokens will be released. */ function releasePAR(address _user) public virtual { UserInfo storage userInfo = _users[_user]; _refresh(); _refreshPAR(totalStake); uint256 pending = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pending); userInfo.accParAmountPerShare = _accParAmountPerShare; require(par.transfer(_user, pending)); } /** Restakes the outstanding PAR reward balance to the user. Instead of sending the PAR to the user, it will be added to their stake @param _user the address of the user for which the PAR tokens will be restaked. */ function restakePAR(address _user) public virtual { UserInfo storage userInfo = _users[_user]; _refresh(); _refreshPAR(totalStake); uint256 pending = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pending); userInfo.accParAmountPerShare = _accParAmountPerShare; _increaseStake(_user, pending); } /** Returns the number of tokens a user has staked. @param _user the address of the user. @return number of staked tokens */ function stake(address _user) public view returns (uint256) { return _users[_user].stake; } /** Returns the number of tokens a user can claim via `releaseMIMO`. @param _user the address of the user. @return number of MIMO tokens that the user can claim */ function pendingMIMO(address _user) public view returns (uint256) { uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); uint256 accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); return _users[_user].stake.rayMul(accAmountPerShare.sub(_users[_user].accAmountPerShare)); } /** Returns the number of PAR tokens the user has earned as a reward @param _user the address of the user. @return nnumber of PAR tokens that will be sent automatically when staking/unstaking */ function pendingPAR(address _user) public view returns (uint256) { uint256 currentBalance = par.balanceOf(address(this)).sub(totalStake); uint256 reward = currentBalance.sub(_parBalanceTracker); uint256 accParAmountPerShare = _accParAmountPerShare.add(reward.rayDiv(totalStake)); return _users[_user].stake.rayMul(accParAmountPerShare.sub(_users[_user].accParAmountPerShare)); } /** Returns the userInfo stored of a user. @param _user the address of the user. @return `struct UserInfo { uint256 stake; uint256 rewardDebt; }` **/ function userInfo(address _user) public view returns (UserInfo memory) { return _users[_user]; } /** Refreshes the global state and subsequently decreases the stake a user has. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be reduced */ function _decreaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message _refresh(); uint256 newTotalStake = totalStake.sub(value); _refreshPAR(newTotalStake); uint256 pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); userInfo.accAmountPerShare = _accAmountPerShare; uint256 pendingPAR = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pendingPAR); userInfo.accParAmountPerShare = _accParAmountPerShare; userInfo.stake = userInfo.stake.sub(value); totalStake = newTotalStake; if (pending > 0) { require(a.mimo().transfer(user, pending)); } if (pendingPAR > 0) { require(par.transfer(user, pendingPAR)); } emit StakeDecreased(user, value); } /** Refreshes the global state and subsequently increases a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param value the amount by which the stake will be increased */ function _increaseStake(address user, uint256 value) internal { require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message UserInfo storage userInfo = _users[user]; _refresh(); uint256 newTotalStake = totalStake.add(value); _refreshPAR(newTotalStake); uint256 pending; uint256 pendingPAR; if (userInfo.stake > 0) { pending = userInfo.stake.rayMul(_accAmountPerShare.sub(userInfo.accAmountPerShare)); _balanceTracker = _balanceTracker.sub(pending); // maybe we should add the accumulated PAR to the stake of the user instead? pendingPAR = userInfo.stake.rayMul(_accParAmountPerShare.sub(userInfo.accParAmountPerShare)); _parBalanceTracker = _parBalanceTracker.sub(pendingPAR); } totalStake = newTotalStake; userInfo.stake = userInfo.stake.add(value); userInfo.accAmountPerShare = _accAmountPerShare; userInfo.accParAmountPerShare = _accParAmountPerShare; if (pendingPAR > 0) { // add pendingPAR balance to stake and totalStake instead of sending it back userInfo.stake = userInfo.stake.add(pendingPAR); totalStake = totalStake.add(pendingPAR); } if (pending > 0) { require(a.mimo().transfer(user, pending)); } emit StakeIncreased(user, value.add(pendingPAR)); } /** Refreshes the global state and subsequently updates a user's stake. This is an internal call and meant to be called within derivative contracts. @param user the address of the user @param stake the new amount of stake for the user */ function _updateStake(address user, uint256 stake) internal returns (bool) { uint256 oldStake = _users[user].stake; if (stake > oldStake) { _increaseStake(user, stake.sub(oldStake)); } if (stake < oldStake) { _decreaseStake(user, oldStake.sub(stake)); } } /** Updates the internal state variables after accounting for newly received MIMO tokens. */ function _refresh() internal { if (totalStake == 0) { return; } uint256 currentBalance = a.mimo().balanceOf(address(this)); uint256 reward = currentBalance.sub(_balanceTracker); _balanceTracker = currentBalance; _accAmountPerShare = _accAmountPerShare.add(reward.rayDiv(totalStake)); } /** Updates the internal state variables after accounting for newly received PAR tokens. */ function _refreshPAR(uint256 newTotalStake) internal { if (totalStake == 0) { return; } uint256 currentParBalance = par.balanceOf(address(this)).sub(newTotalStake); uint256 parReward = currentParBalance.sub(_parBalanceTracker); _parBalanceTracker = currentParBalance; _accParAmountPerShare = _accParAmountPerShare.add(parReward.rayDiv(totalStake)); } } // 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: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./GenericMiner.sol"; import "./interfaces/IMIMO.sol"; import "./interfaces/IDemandMiner.sol"; contract DemandMiner is IDemandMiner, GenericMiner { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public override token; constructor(IGovernanceAddressProvider _addresses, IERC20 _token) public GenericMiner(_addresses) { require(address(_token) != address(0)); require(address(_token) != address(_addresses.mimo())); token = _token; } /** Deposit an ERC20 pool token for staking @dev this function uses `transferFrom()` and requires pre-approval via `approve()` on the ERC20. @param amount the amount of tokens to be deposited. Unit is in WEI. **/ function deposit(uint256 amount) public override { token.safeTransferFrom(msg.sender, address(this), amount); _increaseStake(msg.sender, amount); } /** Withdraw staked ERC20 pool tokens. Will fail if user does not have enough tokens staked. @param amount the amount of tokens to be withdrawn. Unit is in WEI. **/ function withdraw(uint256 amount) public override { token.safeTransfer(msg.sender, amount); _decreaseStake(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./BaseDistributor.sol"; contract EthereumDistributor is BaseDistributor { using SafeMath for uint256; using SafeERC20 for IERC20; constructor(IGovernanceAddressProvider _a) public { require(address(_a) != address(0)); a = _a; } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return a.mimo().balanceOf(address(this)); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); IERC20(a.mimo()).safeTransfer(_payee, payment); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "./interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IGovernorAlpha.sol"; import "./interfaces/ITimelock.sol"; import "./interfaces/IVotingEscrow.sol"; import "../interfaces/IAccessController.sol"; import "../liquidityMining/interfaces/IDebtNotifier.sol"; import "../liquidityMining/interfaces/IMIMO.sol"; contract GovernanceAddressProvider is IGovernanceAddressProvider { IAddressProvider public override parallel; IMIMO public override mimo; IDebtNotifier public override debtNotifier; IGovernorAlpha public override governorAlpha; ITimelock public override timelock; IVotingEscrow public override votingEscrow; constructor(IAddressProvider _parallel) public { require(address(_parallel) != address(0)); parallel = _parallel; } modifier onlyManager() { require(controller().hasRole(controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** Update the `AddressProvider` address that points to main AddressProvider used in the Parallel Protocol @dev only manager can call this. @param _parallel the address of the new `AddressProvider` address. */ function setParallelAddressProvider(IAddressProvider _parallel) public override onlyManager { require(address(_parallel) != address(0)); parallel = _parallel; } /** Update the `MIMO` ERC20 token address @dev only manager can call this. @param _mimo the address of the new `MIMO` token address. */ function setMIMO(IMIMO _mimo) public override onlyManager { require(address(_mimo) != address(0)); mimo = _mimo; } /** Update the `DebtNotifier` address @dev only manager can call this. @param _debtNotifier the address of the new `DebtNotifier`. */ function setDebtNotifier(IDebtNotifier _debtNotifier) public override onlyManager { require(address(_debtNotifier) != address(0)); debtNotifier = _debtNotifier; } /** Update the `GovernorAlpha` address @dev only manager can call this. @param _governorAlpha the address of the new `GovernorAlpha`. */ function setGovernorAlpha(IGovernorAlpha _governorAlpha) public override onlyManager { require(address(_governorAlpha) != address(0)); governorAlpha = _governorAlpha; } /** Update the `Timelock` address @dev only manager can call this. @param _timelock the address of the new `Timelock`. */ function setTimelock(ITimelock _timelock) public override onlyManager { require(address(_timelock) != address(0)); timelock = _timelock; } /** Update the `VotingEscrow` address @dev only manager can call this. @param _votingEscrow the address of the new `VotingEscrow`. */ function setVotingEscrow(IVotingEscrow _votingEscrow) public override onlyManager { require(address(_votingEscrow) != address(0)); votingEscrow = _votingEscrow; } function controller() public view override returns (IAccessController) { return parallel.controller(); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../interfaces/IAddressProvider.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IAccessController.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/ISTABLEX.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IRatesManager.sol"; import "../interfaces/ILiquidationManager.sol"; import "../interfaces/IVaultsCore.sol"; import "../interfaces/IVaultsDataProvider.sol"; contract AddressProvider is IAddressProvider { IAccessController public override controller; IConfigProvider public override config; IVaultsCore public override core; ISTABLEX public override stablex; IRatesManager public override ratesManager; IPriceFeed public override priceFeed; ILiquidationManager public override liquidationManager; IVaultsDataProvider public override vaultsData; IFeeDistributor public override feeDistributor; constructor(IAccessController _controller) public { controller = _controller; } modifier onlyManager() { require(controller.hasRole(controller.MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } function setAccessController(IAccessController _controller) public override onlyManager { require(address(_controller) != address(0)); controller = _controller; } function setConfigProvider(IConfigProvider _config) public override onlyManager { require(address(_config) != address(0)); config = _config; } function setVaultsCore(IVaultsCore _core) public override onlyManager { require(address(_core) != address(0)); core = _core; } function setStableX(ISTABLEX _stablex) public override onlyManager { require(address(_stablex) != address(0)); stablex = _stablex; } function setRatesManager(IRatesManager _ratesManager) public override onlyManager { require(address(_ratesManager) != address(0)); ratesManager = _ratesManager; } function setLiquidationManager(ILiquidationManager _liquidationManager) public override onlyManager { require(address(_liquidationManager) != address(0)); liquidationManager = _liquidationManager; } function setPriceFeed(IPriceFeed _priceFeed) public override onlyManager { require(address(_priceFeed) != address(0)); priceFeed = _priceFeed; } function setVaultsDataProvider(IVaultsDataProvider _vaultsData) public override onlyManager { require(address(_vaultsData) != address(0)); vaultsData = _vaultsData; } function setFeeDistributor(IFeeDistributor _feeDistributor) public override onlyManager { require(address(_feeDistributor) != address(0)); feeDistributor = _feeDistributor; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/ISupplyMiner.sol"; import "../interfaces/IVaultsDataProvider.sol"; contract DebtNotifier is IDebtNotifier { IGovernanceAddressProvider public override a; mapping(address => ISupplyMiner) public override collateralSupplyMinerMapping; constructor(IGovernanceAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyVaultsCore() { require(msg.sender == address(a.parallel().core()), "Caller is not VaultsCore"); _; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender)); _; } /** Notifies the correct supplyMiner of a change in debt. @dev Only the vaultsCore can call this. `debtChanged` will silently return if collateralType is not known to prevent any problems in vaultscore. @param _vaultId the ID of the vault of which the debt has changed. **/ function debtChanged(uint256 _vaultId) public override onlyVaultsCore { IVaultsDataProvider.Vault memory v = a.parallel().vaultsData().vaults(_vaultId); ISupplyMiner supplyMiner = collateralSupplyMinerMapping[v.collateralType]; if (address(supplyMiner) == address(0)) { // not throwing error so VaultsCore keeps working return; } supplyMiner.baseDebtChanged(v.owner, v.baseDebt); } /** Updates the collateral to supplyMiner mapping. @dev Manager role in the AccessController is required to call this. @param collateral the address of the collateralType. @param supplyMiner the address of the supplyMiner which will be notified on debt changes for this collateralType. **/ function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) public override onlyManager { collateralSupplyMinerMapping[collateral] = supplyMiner; } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./GenericMiner.sol"; import "./interfaces/ISupplyMiner.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; contract SupplyMiner is ISupplyMiner, GenericMiner { using SafeMath for uint256; constructor(IGovernanceAddressProvider _addresses) public GenericMiner(_addresses) {} modifier onlyNotifier() { require(msg.sender == address(a.debtNotifier()), "Caller is not DebtNotifier"); _; } /** Gets called by the `DebtNotifier` and will update the stake of the user to match his current outstanding debt by using his baseDebt. @param user address of the user. @param newBaseDebt the new baseDebt and therefore stake for the user. */ function baseDebtChanged(address user, uint256 newBaseDebt) public override onlyNotifier { _updateStake(user, newBaseDebt); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IVaultsDataProvider.sol"; import "../interfaces/IAddressProvider.sol"; contract VaultsDataProvider is IVaultsDataProvider { using SafeMath for uint256; IAddressProvider public override a; uint256 public override vaultCount = 0; mapping(address => uint256) public override baseDebt; mapping(uint256 => Vault) private _vaults; mapping(address => mapping(address => uint256)) private _vaultOwners; modifier onlyVaultsCore() { require(msg.sender == address(a.core()), "Caller is not VaultsCore"); _; } constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Opens a new vault. @dev only the vaultsCore module can call this function @param _collateralType address to the collateral asset e.g. WETH @param _owner the owner of the new vault. */ function createVault(address _collateralType, address _owner) public override onlyVaultsCore returns (uint256) { require(_collateralType != address(0)); require(_owner != address(0)); uint256 newId = ++vaultCount; require(_collateralType != address(0), "collateralType unknown"); Vault memory v = Vault({ collateralType: _collateralType, owner: _owner, collateralBalance: 0, baseDebt: 0, createdAt: block.timestamp }); _vaults[newId] = v; _vaultOwners[_owner][_collateralType] = newId; return newId; } /** Set the collateral balance of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the collateral balance will be updated @param _balance the new balance of the vault. */ function setCollateralBalance(uint256 _id, uint256 _balance) public override onlyVaultsCore { require(vaultExists(_id), "Vault not found."); Vault storage v = _vaults[_id]; v.collateralBalance = _balance; } /** Set the base debt of a vault. @dev only the vaultsCore module can call this function @param _id Vault ID of which the base debt will be updated @param _newBaseDebt the new base debt of the vault. */ function setBaseDebt(uint256 _id, uint256 _newBaseDebt) public override onlyVaultsCore { Vault storage _vault = _vaults[_id]; if (_newBaseDebt > _vault.baseDebt) { uint256 increase = _newBaseDebt.sub(_vault.baseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].add(increase); } else { uint256 decrease = _vault.baseDebt.sub(_newBaseDebt); baseDebt[_vault.collateralType] = baseDebt[_vault.collateralType].sub(decrease); } _vault.baseDebt = _newBaseDebt; } /** Get a vault by vault ID. @param _id The vault's ID to be retrieved @return struct Vault { address collateralType; address owner; uint256 collateralBalance; uint256 baseDebt; uint256 createdAt; } */ function vaults(uint256 _id) public view override returns (Vault memory) { Vault memory v = _vaults[_id]; return v; } /** Get the owner of a vault. @param _id the ID of the vault @return owner of the vault */ function vaultOwner(uint256 _id) public view override returns (address) { return _vaults[_id].owner; } /** Get the collateral type of a vault. @param _id the ID of the vault @return address for the collateral type of the vault */ function vaultCollateralType(uint256 _id) public view override returns (address) { return _vaults[_id].collateralType; } /** Get the collateral balance of a vault. @param _id the ID of the vault @return collateral balance of the vault */ function vaultCollateralBalance(uint256 _id) public view override returns (uint256) { return _vaults[_id].collateralBalance; } /** Get the base debt of a vault. @param _id the ID of the vault @return base debt of the vault */ function vaultBaseDebt(uint256 _id) public view override returns (uint256) { return _vaults[_id].baseDebt; } /** Retrieve the vault id for a specified owner and collateral type. @dev returns 0 for non-existing vaults @param _collateralType address of the collateral type (Eg: WETH) @param _owner address of the owner of the vault @return vault id of the vault or 0 */ function vaultId(address _collateralType, address _owner) public view override returns (uint256) { return _vaultOwners[_owner][_collateralType]; } /** Checks if a specified vault exists. @param _id the ID of the vault @return boolean if the vault exists */ function vaultExists(uint256 _id) public view override returns (bool) { Vault memory v = _vaults[_id]; return v.collateralType != address(0); } /** Calculated the total outstanding debt for all vaults and all collateral types. @dev uses the existing cumulative rate. Call `refresh()` on `VaultsCore` to make sure it's up to date. @return total debt of the platform */ function debt() public view override returns (uint256) { uint256 total = 0; for (uint256 i = 1; i <= a.config().numCollateralConfigs(); i++) { address collateralType = a.config().collateralConfigs(i).collateralType; total = total.add(collateralDebt(collateralType)); } return total; } /** Calculated the total outstanding debt for all vaults of a specific collateral type. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _collateralType address of the collateral type (Eg: WETH) @return total debt of the platform of one collateral type */ function collateralDebt(address _collateralType) public view override returns (uint256) { return a.ratesManager().calculateDebt(baseDebt[_collateralType], a.core().cumulativeRates(_collateralType)); } /** Calculated the total outstanding debt for a specific vault. @dev uses the existing cumulative rate. Call `refreshCollateral()` on `VaultsCore` to make sure it's up to date. @param _vaultId the ID of the vault @return total debt of one vault */ function vaultDebt(uint256 _vaultId) public view override returns (uint256) { IVaultsDataProvider.Vault memory v = _vaults[_vaultId]; return a.ratesManager().calculateDebt(v.baseDebt, a.core().cumulativeRates(v.collateralType)); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/ILiquidationManager.sol"; import "../interfaces/IAddressProvider.sol"; contract LiquidationManager is ILiquidationManager, ReentrancyGuard { using SafeMath for uint256; using WadRayMath for uint256; IAddressProvider public override a; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18; // 1 constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Check if the health factor is above or equal to 1. @param _collateralValue value of the collateral in PAR @param _vaultDebt outstanding debt to which the collateral balance shall be compared @param _minRatio min ratio to calculate health factor @return boolean if the health factor is >= 1. */ function isHealthy( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) public view override returns (bool) { uint256 healthFactor = calculateHealthFactor(_collateralValue, _vaultDebt, _minRatio); return healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } /** Calculate the healthfactor of a debt balance @param _collateralValue value of the collateral in PAR currency @param _vaultDebt outstanding debt to which the collateral balance shall be compared @param _minRatio min ratio to calculate health factor @return healthFactor */ function calculateHealthFactor( uint256 _collateralValue, uint256 _vaultDebt, uint256 _minRatio ) public view override returns (uint256 healthFactor) { if (_vaultDebt == 0) return WadRayMath.wad(); // CurrentCollateralizationRatio = value(deposited ETH) / debt uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt); // Healthfactor = CurrentCollateralizationRatio / MinimumCollateralizationRatio if (_minRatio > 0) { return collateralizationRatio.wadDiv(_minRatio); } return 1e18; // 1 } /** Calculate the liquidation bonus for a specified amount @param _collateralType address of the collateral type @param _amount amount for which the liquidation bonus shall be calculated @return bonus the liquidation bonus to pay out */ function liquidationBonus(address _collateralType, uint256 _amount) public view override returns (uint256 bonus) { return _amount.wadMul(a.config().collateralLiquidationBonus(_collateralType)); } /** Apply the liquidation bonus to a balance as a discount. @param _collateralType address of the collateral type @param _amount the balance on which to apply to liquidation bonus as a discount. @return discountedAmount */ function applyLiquidationDiscount(address _collateralType, uint256 _amount) public view override returns (uint256 discountedAmount) { return _amount.wadDiv(a.config().collateralLiquidationBonus(_collateralType).add(WadRayMath.wad())); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/ISTABLEX.sol"; import "../interfaces/IFeeDistributor.sol"; import "../interfaces/IAddressProvider.sol"; contract FeeDistributor is IFeeDistributor, ReentrancyGuard { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event FeeReleased(uint256 income, uint256 releasedAt); uint256 public override lastReleasedAt; IAddressProvider public override a; uint256 public override totalShares; mapping(address => uint256) public override shares; address[] public payees; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Public function to release the accumulated fee income to the payees. @dev anyone can call this. */ function release() public override nonReentrant { uint256 income = a.core().state().availableIncome(); require(income > 0, "income is 0"); require(payees.length > 0, "Payees not configured yet"); lastReleasedAt = now; // Mint USDX to all receivers for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(income, payee); } emit FeeReleased(income, lastReleasedAt); } /** Updates the payee configuration to a new one. @dev will release existing fees before the update. @param _payees Array of payees @param _shares Array of shares for each payee */ function changePayees(address[] memory _payees, uint256[] memory _shares) public override onlyManager { require(_payees.length == _shares.length, "Payees and shares mismatched"); require(_payees.length > 0, "No payees"); uint256 income = a.core().state().availableIncome(); if (income > 0 && payees.length > 0) { release(); } for (uint256 i = 0; i < payees.length; i++) { delete shares[payees[i]]; } delete payees; totalShares = 0; for (uint256 i = 0; i < _payees.length; i++) { _addPayee(_payees[i], _shares[i]); } } /** Get current configured payees. @return array of current payees. */ function getPayees() public view override returns (address[] memory) { return payees; } /** Internal function to release a percentage of income to a specific payee @dev uses totalShares to calculate correct share @param _totalIncomeReceived Total income for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalIncomeReceived, address _payee) internal { uint256 payment = _totalIncomeReceived.mul(shares[_payee]).div(totalShares); a.stablex().mint(_payee, payment); } /** Internal function to add a new payee. @dev will update totalShares and therefore reduce the relative share of all other payees. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee. */ function _addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0), "payee is the zero address"); require(_shares > 0, "shares are 0"); require(shares[_payee] == 0, "payee already has shares"); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); emit PayeeAdded(_payee, _shares); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../interfaces/IRatesManager.sol"; import "../interfaces/IAddressProvider.sol"; contract RatesManager is IRatesManager { using SafeMath for uint256; using WadRayMath for uint256; uint256 private constant _SECONDS_PER_YEAR = 365 days; IAddressProvider public override a; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } /** Calculate the annualized borrow rate from the specified borrowing rate. @param _borrowRate rate for a 1 second interval specified in RAY accuracy. @return annualized rate */ function annualizedBorrowRate(uint256 _borrowRate) public pure override returns (uint256) { return _borrowRate.rayPow(_SECONDS_PER_YEAR); } /** Calculate the total debt from a specified base debt and cumulative rate. @param _baseDebt the base debt to be used. Can be a vault base debt or an aggregate base debt @param _cumulativeRate the cumulative rate in RAY accuracy. @return debt after applying the cumulative rate */ function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) public pure override returns (uint256 debt) { return _baseDebt.rayMul(_cumulativeRate); } /** Calculate the base debt from a specified total debt and cumulative rate. @param _debt the total debt to be used. @param _cumulativeRate the cumulative rate in RAY accuracy. @return baseDebt the new base debt */ function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) public pure override returns (uint256 baseDebt) { return _debt.rayDiv(_cumulativeRate); } /** Bring an existing cumulative rate forward in time @param _borrowRate rate for a 1 second interval specified in RAY accuracy to be applied @param _timeElapsed the time over whicht the borrow rate shall be applied @param _cumulativeRate the initial cumulative rate from which to apply the borrow rate @return new cumulative rate */ function calculateCumulativeRate( uint256 _borrowRate, uint256 _cumulativeRate, uint256 _timeElapsed ) public view override returns (uint256) { if (_timeElapsed == 0) return _cumulativeRate; uint256 cumulativeElapsed = _borrowRate.rayPow(_timeElapsed); return _cumulativeRate.rayMul(cumulativeElapsed); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../interfaces/IPriceFeed.sol"; import "../interfaces/IAddressProvider.sol"; import "../chainlink/AggregatorV3Interface.sol"; import "../libraries/MathPow.sol"; import "../libraries/WadRayMath.sol"; contract PriceFeed is IPriceFeed { using SafeMath for uint256; using SafeMath for uint8; using WadRayMath for uint256; uint256 public constant PRICE_ORACLE_STALE_THRESHOLD = 1 days; IAddressProvider public override a; mapping(address => AggregatorV3Interface) public override assetOracles; AggregatorV3Interface public override eurOracle; constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** * @notice Sets the oracle for the given asset, * @param _asset address to the collateral asset e.g. WETH * @param _oracle address to the oracel, this oracle should implement the AggregatorV3Interface */ function setAssetOracle(address _asset, address _oracle) public override onlyManager { require(_asset != address(0)); require(_oracle != address(0)); assetOracles[_asset] = AggregatorV3Interface(_oracle); emit OracleUpdated(_asset, _oracle, msg.sender); } /** * @notice Sets the oracle for EUR, this oracle should provide EUR-USD prices * @param _oracle address to the oracle, this oracle should implement the AggregatorV3Interface */ function setEurOracle(address _oracle) public override onlyManager { require(_oracle != address(0)); eurOracle = AggregatorV3Interface(_oracle); emit EurOracleUpdated(_oracle, msg.sender); } /** * Gets the asset price in EUR (PAR) * @dev returned value has matching decimals to the asset oracle (not the EUR oracle) * @param _asset address to the collateral asset e.g. WETH */ function getAssetPrice(address _asset) public view override returns (uint256 price) { (, int256 eurAnswer, , uint256 eurUpdatedAt, ) = eurOracle.latestRoundData(); require(eurAnswer > 0, "EUR price data not valid"); require(block.timestamp - eurUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "EUR price data is stale"); (, int256 answer, , uint256 assetUpdatedAt, ) = assetOracles[_asset].latestRoundData(); require(answer > 0, "Price data not valid"); require(block.timestamp - assetUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "Price data is stale"); uint8 eurDecimals = eurOracle.decimals(); uint256 eurAccuracy = MathPow.pow(10, eurDecimals); return uint256(answer).mul(eurAccuracy).div(uint256(eurAnswer)); } /** * @notice Converts asset balance into stablecoin balance at current price * @param _asset address to the collateral asset e.g. WETH * @param _amount amount of collateral */ function convertFrom(address _asset, uint256 _amount) public view override returns (uint256) { uint256 price = getAssetPrice(_asset); uint8 collateralDecimals = ERC20(_asset).decimals(); uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals() uint8 oracleDecimals = assetOracles[_asset].decimals(); uint256 parAccuracy = MathPow.pow(10, parDecimals); uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals)); return _amount.mul(price).mul(parAccuracy).div(collateralAccuracy); } /** * @notice Converts stablecoin balance into collateral balance at current price * @param _asset address to the collateral asset e.g. WETH * @param _amount amount of stablecoin */ function convertTo(address _asset, uint256 _amount) public view override returns (uint256) { uint256 price = getAssetPrice(_asset); uint8 collateralDecimals = ERC20(_asset).decimals(); uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals() uint8 oracleDecimals = assetOracles[_asset].decimals(); uint256 parAccuracy = MathPow.pow(10, parDecimals); uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals)); return _amount.mul(collateralAccuracy).div(price).div(parAccuracy); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; library MathPow { function pow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : 1; for (n /= 2; n != 0; n /= 2) { x = SafeMath.mul(x, x); if (n % 2 != 0) { z = SafeMath.mul(z, x); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "../chainlink/AggregatorV3Interface.sol"; contract MockChainlinkFeed is AggregatorV3Interface, Ownable { uint256 private _latestPrice; string public override description; uint256 public override version = 3; uint8 public override decimals; constructor( uint8 _decimals, uint256 _price, string memory _description ) public { decimals = _decimals; _latestPrice = _price; description = _description; } function setLatestPrice(uint256 price) public onlyOwner { require(price > 110033500); // > 1.1 USD require(price < 130033500); // > 1.3 USD _latestPrice = price; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = uint80(_roundId); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = uint256(1597695228); answeredInRound = uint80(_roundId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { uint256 latestRound = 101; roundId = uint80(latestRound); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = now; answeredInRound = uint80(latestRound); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../chainlink/AggregatorV3Interface.sol"; contract MockChainlinkAggregator is AggregatorV3Interface { uint256 private _latestPrice; uint256 private _updatedAt; string public override description; uint256 public override version = 3; uint8 public override decimals; constructor( uint8 _decimals, uint256 _price, string memory _description ) public { decimals = _decimals; _latestPrice = _price; description = _description; } function setLatestPrice(uint256 price) public { _latestPrice = price; } function setUpdatedAt(uint256 updatedAt) public { _updatedAt = updatedAt; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = uint80(_roundId); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = uint256(1597695228); answeredInRound = uint80(_roundId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { uint256 latestRound = 101; roundId = uint80(latestRound); answer = int256(_latestPrice); startedAt = uint256(1597422127); updatedAt = _updatedAt; answeredInRound = uint80(latestRound); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "../libraries/WadRayMath.sol"; import "../interfaces/IConfigProvider.sol"; import "../interfaces/IAddressProvider.sol"; contract ConfigProvider is IConfigProvider { IAddressProvider public override a; mapping(uint256 => CollateralConfig) private _collateralConfigs; //indexing starts at 1 mapping(address => uint256) public override collateralIds; uint256 public override numCollateralConfigs; /// @notice The minimum duration of voting on a proposal, in seconds uint256 public override minVotingPeriod = 3 days; /// @notice The max duration of voting on a proposal, in seconds uint256 public override maxVotingPeriod = 2 weeks; /// @notice The percentage of votes in support of a proposal required in order for a quorum to be reached and for a proposal to succeed uint256 public override votingQuorum = 1e16; // 1% /// @notice The percentage of votes required in order for a voter to become a proposer uint256 public override proposalThreshold = 2e14; // 0.02% constructor(IAddressProvider _addresses) public { require(address(_addresses) != address(0)); a = _addresses; } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } /** Creates or overwrites an existing config for a collateral type @param _collateralType address of the collateral type @param _debtLimit the debt ceiling for the collateral type @param _liquidationRatio the minimum ratio to maintain to avoid liquidation @param _minCollateralRatio the minimum ratio to maintain to borrow new money or withdraw collateral @param _borrowRate the borrowing rate specified in 1 second interval in RAY accuracy. @param _originationFee an optional origination fee for newly created debt. Can be 0. @param _liquidationBonus the liquidation bonus to be paid to liquidators. @param _liquidationFee an optional fee for liquidation debt. Can be 0. */ function setCollateralConfig( address _collateralType, uint256 _debtLimit, uint256 _liquidationRatio, uint256 _minCollateralRatio, uint256 _borrowRate, uint256 _originationFee, uint256 _liquidationBonus, uint256 _liquidationFee ) public override onlyManager { require(address(_collateralType) != address(0)); require(_minCollateralRatio >= _liquidationRatio); if (collateralIds[_collateralType] == 0) { // Initialize new collateral a.core().state().initializeRates(_collateralType); CollateralConfig memory config = CollateralConfig({ collateralType: _collateralType, debtLimit: _debtLimit, liquidationRatio: _liquidationRatio, minCollateralRatio: _minCollateralRatio, borrowRate: _borrowRate, originationFee: _originationFee, liquidationBonus: _liquidationBonus, liquidationFee: _liquidationFee }); numCollateralConfigs++; _collateralConfigs[numCollateralConfigs] = config; collateralIds[_collateralType] = numCollateralConfigs; } else { // Update collateral config a.core().state().refreshCollateral(_collateralType); uint256 id = collateralIds[_collateralType]; _collateralConfigs[id].collateralType = _collateralType; _collateralConfigs[id].debtLimit = _debtLimit; _collateralConfigs[id].liquidationRatio = _liquidationRatio; _collateralConfigs[id].minCollateralRatio = _minCollateralRatio; _collateralConfigs[id].borrowRate = _borrowRate; _collateralConfigs[id].originationFee = _originationFee; _collateralConfigs[id].liquidationBonus = _liquidationBonus; _collateralConfigs[id].liquidationFee = _liquidationFee; } emit CollateralUpdated( _collateralType, _debtLimit, _liquidationRatio, _minCollateralRatio, _borrowRate, _originationFee, _liquidationBonus, _liquidationFee ); } function _emitUpdateEvent(address _collateralType) internal { emit CollateralUpdated( _collateralType, _collateralConfigs[collateralIds[_collateralType]].debtLimit, _collateralConfigs[collateralIds[_collateralType]].liquidationRatio, _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio, _collateralConfigs[collateralIds[_collateralType]].borrowRate, _collateralConfigs[collateralIds[_collateralType]].originationFee, _collateralConfigs[collateralIds[_collateralType]].liquidationBonus, _collateralConfigs[collateralIds[_collateralType]].liquidationFee ); } /** Remove the config for a collateral type @param _collateralType address of the collateral type */ function removeCollateral(address _collateralType) public override onlyManager { uint256 id = collateralIds[_collateralType]; require(id != 0, "collateral does not exist"); _collateralConfigs[id] = _collateralConfigs[numCollateralConfigs]; //move last entry forward collateralIds[_collateralConfigs[id].collateralType] = id; //update id for last entry delete _collateralConfigs[numCollateralConfigs]; // delete last entry delete collateralIds[_collateralType]; numCollateralConfigs--; emit CollateralRemoved(_collateralType); } /** Sets the debt limit for a collateral type @param _collateralType address of the collateral type @param _debtLimit the new debt limit */ function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].debtLimit = _debtLimit; _emitUpdateEvent(_collateralType); } /** Sets the minimum liquidation ratio for a collateral type @dev this is the liquidation treshold under which a vault is considered open for liquidation. @param _collateralType address of the collateral type @param _liquidationRatio the new minimum collateralization ratio */ function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) public override onlyManager { require(_liquidationRatio <= _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio); _collateralConfigs[collateralIds[_collateralType]].liquidationRatio = _liquidationRatio; _emitUpdateEvent(_collateralType); } /** Sets the minimum ratio for a collateral type for new borrowing or collateral withdrawal @param _collateralType address of the collateral type @param _minCollateralRatio the new minimum open ratio */ function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) public override onlyManager { require(_minCollateralRatio >= _collateralConfigs[collateralIds[_collateralType]].liquidationRatio); _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio = _minCollateralRatio; _emitUpdateEvent(_collateralType); } /** Sets the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type @param _borrowRate the new borrowing rate for a 1 sec interval */ function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) public override onlyManager { a.core().state().refreshCollateral(_collateralType); _collateralConfigs[collateralIds[_collateralType]].borrowRate = _borrowRate; _emitUpdateEvent(_collateralType); } /** Sets the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type @param _originationFee new origination fee in WAD */ function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].originationFee = _originationFee; _emitUpdateEvent(_collateralType); } /** Sets the liquidation bonus for a collateral type @dev the liquidation bonus is specified in WAD @param _collateralType address of the collateral type @param _liquidationBonus the liquidation bonus to be paid to liquidators. */ function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) public override onlyManager { _collateralConfigs[collateralIds[_collateralType]].liquidationBonus = _liquidationBonus; _emitUpdateEvent(_collateralType); } /** Sets the liquidation fee for a collateral type @dev this rate is applied as a fee for liquidation and is specified in WAD @param _collateralType address of the collateral type @param _liquidationFee new liquidation fee in WAD */ function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) public override onlyManager { require(_liquidationFee < 1e18); // fee < 100% _collateralConfigs[collateralIds[_collateralType]].liquidationFee = _liquidationFee; _emitUpdateEvent(_collateralType); } /** Set the min voting period for a gov proposal. @param _minVotingPeriod the min voting period for a gov proposal */ function setMinVotingPeriod(uint256 _minVotingPeriod) public override onlyManager { minVotingPeriod = _minVotingPeriod; } /** Set the max voting period for a gov proposal. @param _maxVotingPeriod the max voting period for a gov proposal */ function setMaxVotingPeriod(uint256 _maxVotingPeriod) public override onlyManager { maxVotingPeriod = _maxVotingPeriod; } /** Set the voting quora for a gov proposal. @param _votingQuorum the voting quora for a gov proposal */ function setVotingQuorum(uint256 _votingQuorum) public override onlyManager { require(_votingQuorum < 1e18); votingQuorum = _votingQuorum; } /** Set the proposal threshold for a gov proposal. @param _proposalThreshold the proposal threshold for a gov proposal */ function setProposalThreshold(uint256 _proposalThreshold) public override onlyManager { require(_proposalThreshold < 1e18); proposalThreshold = _proposalThreshold; } /** Get the debt limit for a collateral type @dev this is a platform wide limit for new debt issuance against a specific collateral type @param _collateralType address of the collateral type */ function collateralDebtLimit(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].debtLimit; } /** Get the liquidation ratio that needs to be maintained for a collateral type to avoid liquidation. @param _collateralType address of the collateral type */ function collateralLiquidationRatio(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].liquidationRatio; } /** Get the minimum collateralization ratio for a collateral type for new borrowing or collateral withdrawal. @param _collateralType address of the collateral type */ function collateralMinCollateralRatio(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].minCollateralRatio; } /** Get the borrowing rate for a collateral type @dev borrowing rate is specified for a 1 sec interval and accurancy is in RAY. @param _collateralType address of the collateral type */ function collateralBorrowRate(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].borrowRate; } /** Get the origiation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralOriginationFee(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].originationFee; } /** Get the liquidation bonus for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralLiquidationBonus(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].liquidationBonus; } /** Get the liquidation fee for a collateral type @dev this rate is applied as a one time fee for new borrowing and is specified in WAD @param _collateralType address of the collateral type */ function collateralLiquidationFee(address _collateralType) public view override returns (uint256) { return _collateralConfigs[collateralIds[_collateralType]].liquidationFee; } /** Retreives the entire config for a specific config id. @param _id the ID of the conifg to be returned */ function collateralConfigs(uint256 _id) public view override returns (CollateralConfig memory) { require(_id <= numCollateralConfigs, "Invalid config id"); return _collateralConfigs[_id]; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/ITimelock.sol"; contract Timelock is ITimelock { using SafeMath for uint256; uint256 public constant MINIMUM_DELAY = 2 days; uint256 public constant MAXIMUM_DELAY = 30 days; uint256 public constant override GRACE_PERIOD = 14 days; address public admin; address public pendingAdmin; uint256 public override delay; mapping(bytes32 => bool) public override queuedTransactions; constructor(address _admin, uint256 _delay) public { require(address(_admin) != address(0)); require(_delay >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); admin = _admin; delay = _delay; } receive() external payable {} fallback() external payable {} function setDelay(uint256 _delay) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(_delay >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = _delay; emit NewDelay(delay); } function acceptAdmin() public override { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address _pendingAdmin) public { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); pendingAdmin = _pendingAdmin; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public override returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require( eta >= block.timestamp.add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay." ); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public override { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable override returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(block.timestamp >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(block.timestamp <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{ value: value }(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; import '../Timelock.sol'; // Test timelock contract with admin helpers contract TestTimelock is Timelock { constructor(address admin_, uint256 delay_) public Timelock(admin_, 2 days) { delay = delay_; } function harnessSetPendingAdmin(address pendingAdmin_) public { pendingAdmin = pendingAdmin_; } function harnessSetAdmin(address admin_) public { admin = admin_; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IGovernorAlpha.sol"; import "./interfaces/IGovernanceAddressProvider.sol"; import "../libraries/WadRayMath.sol"; contract GovernorAlpha is IGovernorAlpha { using SafeMath for uint256; using WadRayMath for uint256; /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions IGovernanceAddressProvider public a; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint256 public proposalCount; /// @notice The official record of all proposals ever proposed mapping(uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping(address => uint256) public latestProposalIds; constructor(IGovernanceAddressProvider _addresses, address _guardian) public { require(address(_addresses) != address(0)); require(address(_guardian) != address(0)); a = _addresses; guardian = _guardian; } function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, uint256 endTime ) public override returns (uint256) { uint256 votingDuration = endTime.sub(block.timestamp); require(votingDuration >= a.parallel().config().minVotingPeriod(), "Proposal end-time too early"); require(votingDuration <= a.parallel().config().maxVotingPeriod(), "Proposal end-time too late"); require( a.votingEscrow().balanceOfAt(msg.sender, endTime) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold" ); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch" ); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require( proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal" ); } proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startTime: block.timestamp, endTime: endTime, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, targets, values, signatures, calldatas, block.timestamp, endTime, description ); return newProposal.id; } function queue(uint256 proposalId) public override { require( state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded" ); Proposal storage proposal = proposals[proposalId]; uint256 eta = block.timestamp.add(a.timelock().delay()); for (uint256 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 execute(uint256 proposalId) public payable override { require( state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued" ); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { a.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(uint256 proposalId) public override { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian, "Only Guardian can cancel"); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { a.timelock().cancelTransaction( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta ); } emit ProposalCanceled(proposalId); } function castVote(uint256 proposalId, bool support) public override { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[msg.sender]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint256 votes = a.votingEscrow().balanceOfAt(msg.sender, proposal.endTime); if (support) { proposal.forVotes = proposal.forVotes.add(votes); } else { proposal.againstVotes = proposal.againstVotes.add(votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(msg.sender, proposalId, support, votes); } // solhint-disable-next-line private-vars-leading-underscore function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); a.timelock().acceptAdmin(); } // solhint-disable-next-line private-vars-leading-underscore function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } // solhint-disable-next-line private-vars-leading-underscore function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); a.timelock().queueTransaction( address(a.timelock()), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta ); } // solhint-disable-next-line private-vars-leading-underscore function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); a.timelock().executeTransaction( address(a.timelock()), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta ); } /// @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 view override returns (uint256) { return a.votingEscrow().stakingToken().totalSupply().wadMul(a.parallel().config().votingQuorum()); } /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public view override returns (uint256) { return a.votingEscrow().stakingToken().totalSupply().wadMul(a.parallel().config().proposalThreshold()); } function getActions(uint256 proposalId) public view override returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint256 proposalId, address voter) public view override returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint256 proposalId) public view override returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= a.timelock().GRACE_PERIOD().add(proposal.endTime)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _queueOrRevert( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require( !a.timelock().queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta" ); a.timelock().queueTransaction(target, value, signature, data, eta); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/WadRayMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IMIMODistributor.sol"; import "./BaseDistributor.sol"; /* Distribution Formula: 55.5m MIMO in first week -5.55% redution per week total(timestamp) = _SECONDS_PER_WEEK * ( (1-_WEEKLY_R^(timestamp/_SECONDS_PER_WEEK)) / (1-_WEEKLY_R) ) + timestamp % _SECONDS_PER_WEEK * (1-_WEEKLY_R^(timestamp/_SECONDS_PER_WEEK) */ contract MIMODistributor is BaseDistributor, IMIMODistributorExtension { using SafeMath for uint256; using WadRayMath for uint256; uint256 private constant _SECONDS_PER_YEAR = 365 days; uint256 private constant _SECONDS_PER_WEEK = 7 days; uint256 private constant _WEEKLY_R = 9445e23; //-5.55% uint256 private constant _FIRST_WEEK_TOKENS = 55500000 ether; //55.5m uint256 public override startTime; constructor(IGovernanceAddressProvider _a, uint256 _startTime) public { require(address(_a) != address(0)); a = _a; startTime = _startTime; } /** Get current monthly issuance of new MIMO tokens. @return number of monthly issued tokens currently`. */ function currentIssuance() public view override returns (uint256) { return weeklyIssuanceAt(now); } /** Get monthly issuance of new MIMO tokens at `timestamp`. @dev invalid for timestamps before deployment @param timestamp for which to calculate the monthly issuance @return number of monthly issued tokens at `timestamp`. */ function weeklyIssuanceAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); return _WEEKLY_R.rayPow(elapsedWeeks).rayMul(_FIRST_WEEK_TOKENS); } /** Calculates how many MIMO tokens can be minted since the last time tokens were minted @return number of mintable tokens available right now. */ function mintableTokens() public view override returns (uint256) { return totalSupplyAt(now).sub(a.mimo().totalSupply()); } /** Calculates the totalSupply for any point after `startTime` @param timestamp for which to calculate the totalSupply @return totalSupply at timestamp. */ function totalSupplyAt(uint256 timestamp) public view override returns (uint256) { uint256 elapsedSeconds = timestamp.sub(startTime); uint256 elapsedWeeks = elapsedSeconds.div(_SECONDS_PER_WEEK); uint256 lastWeekSeconds = elapsedSeconds % _SECONDS_PER_WEEK; uint256 one = WadRayMath.ray(); uint256 fullWeeks = one.sub(_WEEKLY_R.rayPow(elapsedWeeks)).rayMul(_FIRST_WEEK_TOKENS).rayDiv(one.sub(_WEEKLY_R)); uint256 currentWeekIssuance = weeklyIssuanceAt(timestamp); uint256 partialWeek = currentWeekIssuance.mul(lastWeekSeconds).div(_SECONDS_PER_WEEK); return fullWeeks.add(partialWeek); } /** Internal function to release a percentage of newTokens to a specific payee @dev uses totalShares to calculate correct share @param _totalnewTokensReceived Total newTokens for all payees, will be split according to shares @param _payee The address of the payee to whom to distribute the fees. */ function _release(uint256 _totalnewTokensReceived, address _payee) internal override { uint256 payment = _totalnewTokensReceived.mul(shares[_payee]).div(totalShares); a.mimo().mint(_payee, payment); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../governance/interfaces/IGovernanceAddressProvider.sol"; import "./interfaces/IBaseDistributor.sol"; contract DistributorManager { using SafeMath for uint256; IGovernanceAddressProvider public a; IBaseDistributor public mimmoDistributor; modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not Manager"); _; } constructor(IGovernanceAddressProvider _a, IBaseDistributor _mimmoDistributor) public { require(address(_a) != address(0)); require(address(_mimmoDistributor) != address(0)); a = _a; mimmoDistributor = _mimmoDistributor; } /** Public function to release the accumulated new MIMO tokens to the payees. @dev anyone can call this. */ function releaseAll() public { mimmoDistributor.release(); address[] memory distributors = mimmoDistributor.getPayees(); for (uint256 i = 0; i < distributors.length; i++) { IBaseDistributor(distributors[i]).release(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockWETH is ERC20("Wrapped Ether", "WETH") { function mint(address account, uint256 amount) public { _mint(account, amount); } function deposit() public payable { _mint(msg.sender, msg.value); } function withdraw(uint256 wad) public { _burn(msg.sender, wad); msg.sender.transfer(wad); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockWBTC is ERC20("Wrapped Bitcoin", "WBTC") { function mint(address account, uint256 amount) public { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockMIMO is ERC20("MIMO Token", "MIMO") { function mint(address account, uint256 amount) public { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockERC20 is ERC20 { constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { super._setupDecimals(_decimals); } function mint(address account, uint256 amount) public { _mint(account, amount); } function burn(address account, uint256 amount) public { _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockBPT is ERC20("Balancer Pool Token", "BPT") { function mint(address account, uint256 amount) public { _mint(account, amount); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IAddressProvider.sol"; import "../libraries/interfaces/IVault.sol"; contract MIMOBuyback { bytes32 public constant KEEPER_ROLE = keccak256("KEEPER_ROLE"); IAddressProvider public a; IERC20 public PAR; IERC20 public MIMO; uint256 public lockExpiry; bytes32 public poolID; IVault public balancer = IVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8); bool public whitelistEnabled = false; constructor( uint256 _lockExpiry, bytes32 _poolID, address _a, address _mimo ) public { lockExpiry = _lockExpiry; poolID = _poolID; a = IAddressProvider(_a); MIMO = IERC20(_mimo); PAR = a.stablex(); PAR.approve(address(balancer), 2**256 - 1); } modifier onlyManager() { require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager"); _; } modifier onlyKeeper() { require( !whitelistEnabled || (whitelistEnabled && a.controller().hasRole(KEEPER_ROLE, msg.sender)), "Caller is not a Keeper" ); _; } function withdrawMIMO(address destination) public onlyManager { require(block.timestamp > lockExpiry, "lock not expired yet"); require(MIMO.transfer(destination, MIMO.balanceOf(address(this)))); } function buyMIMO() public onlyKeeper { a.core().state().refresh(); a.feeDistributor().release(); bytes memory userData = abi.encode(); IVault.SingleSwap memory singleSwap = IVault.SingleSwap( poolID, IVault.SwapKind.GIVEN_IN, IAsset(address(PAR)), // swap in IAsset(address(MIMO)), // swap out PAR.balanceOf(address(this)), // all PAR of this contract userData ); IVault.FundManagement memory fundManagement = IVault.FundManagement( address(this), // sender false, // useInternalBalance payable(address(this)), // recipient false // // useInternalBalance ); balancer.swap( singleSwap, fundManagement, 0, // limit, could be frontrun? 2**256 - 1 // deadline ); } function setWhitelistEnabled(bool _status) public onlyManager { whitelistEnabled = _status; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAsset { // solhint-disable-previous-line no-empty-blocks } interface IVault { enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; /** Buggy ERC20 implementation without the return bool on `transfer`, `transferFrom` and `approve` for testing purposes */ contract MockBuggyERC20 is Context { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual { _transfer(_msgSender(), recipient, amount); } function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual { _approve(_msgSender(), spender, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance") ); } function mint(address account, uint256 amount) public { _mint(account, amount); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal 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); } 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); } 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 _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity 0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface BPool is IERC20 { function gulp(address token) external; function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external; function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external; function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter); function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter); function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external returns (uint256 poolAmountOut); function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external returns (uint256 tokenAmountIn); function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external returns (uint256 tokenAmountOut); function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external returns (uint256 poolAmountIn); function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) external pure returns (uint256 poolAmountOut); function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice); function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice); function getSwapFee() external view returns (uint256); function getBalance(address token) external view returns (uint256); function getDenormalizedWeight(address token) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getNormalizedWeight(address token) external view returns (uint256); function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); }
/make sure current rate is up to date
function borrow(uint256 _vaultId, uint256 _amount) public override onlyVaultOwner(_vaultId) nonReentrant { IVaultsDataProvider.Vault memory v = a.vaultsData().vaults(_vaultId); refreshCollateral(v.collateralType); uint256 originationFeePercentage = a.config().collateralOriginationFee(v.collateralType); uint256 newDebt = _amount; if (originationFeePercentage > 0) { newDebt = newDebt.add(_amount.wadMul(originationFeePercentage)); } a.vaultsData().setBaseDebt(_vaultId, v.baseDebt.add(newBaseDebt)); uint256 collateralValue = a.priceFeed().convertFrom(v.collateralType, v.collateralBalance); uint256 newVaultDebt = a.vaultsData().vaultDebt(_vaultId); require(a.vaultsData().collateralDebt(v.collateralType) <= a.config().collateralDebtLimit(v.collateralType)); bool isHealthy = ILiquidationManagerV1(address(a.liquidationManager())).isHealthy( v.collateralType, collateralValue, newVaultDebt ); require(isHealthy); a.stablex().mint(msg.sender, _amount); emit Borrowed(_vaultId, _amount, msg.sender); }
12,889,181
/* * Copyright ©️ 2018 Galt•Space Society Construction and Terraforming Company * (Founded by [Nikolai Popeka](https://github.com/npopeka), * [Dima Starodubcev](https://github.com/xhipster), * [Valery Litvin](https://github.com/litvintech) by * [Basic Agreement](http://cyb.ai/QmSAWEG5u5aSsUyMNYuX2A2Eaz4kEuoYWUkVBRdmu9qmct:ipfs)). * * Copyright ©️ 2018 Galt•Core Blockchain Company * (Founded by [Nikolai Popeka](https://github.com/npopeka) and * Galt•Space Society Construction and Terraforming Company by * [Basic Agreement](http://cyb.ai/QmaCiXUmSrP16Gz8Jdzq6AJESY1EAANmmwha15uR3c1bsS:ipfs)). */ pragma solidity 0.5.10; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "@galtproject/geodesic/contracts/interfaces/IGeodesic.sol"; import "../interfaces/ISpaceToken.sol"; import "../registries/interfaces/ISpaceGeoDataRegistry.sol"; import "./interfaces/IPropertyManagerFeeCalculator.sol"; import "./AbstractApplication.sol"; import "./AbstractOracleApplication.sol"; import "./NewPropertyManagerLib.sol"; import "../registries/GaltGlobalRegistry.sol"; import "../registries/interfaces/IPGGRegistry.sol"; contract NewPropertyManager is AbstractOracleApplication { using SafeMath for uint256; bytes32 public constant PM_LAWYER_ORACLE_TYPE = bytes32("PM_LAWYER_ORACLE_TYPE"); bytes32 public constant PM_SURVEYOR_ORACLE_TYPE = bytes32("PM_SURVEYOR_ORACLE_TYPE"); bytes32 public constant APPLICATION_UNLOCKER = bytes32("application_unlocker"); bytes32 public constant CONFIG_FEE_CALCULATOR = bytes32("PM_FEE_CALCULATOR"); bytes32 public constant CONFIG_PAYMENT_METHOD = bytes32("PM_PAYMENT_METHOD"); bytes32 public constant CONFIG_PREFIX = bytes32("PM"); event NewSpaceToken(address indexed applicant, uint256 spaceTokenId, bytes32 applicationId); event NewApplication(address indexed applicant, bytes32 applicationId); event ApplicationStatusChanged(bytes32 indexed applicationId, ApplicationStatus indexed status); event ValidationStatusChanged(bytes32 indexed applicationId, bytes32 indexed oracleType, ValidationStatus indexed status); event OracleRewardClaim(bytes32 indexed applicationId, address indexed oracle); event GaltProtocolFeeAssigned(bytes32 indexed applicationId); event ClaimSpaceToken(bytes32 indexed applicationId, uint256 indexed spaceTokenId); enum ApplicationStatus { NOT_EXISTS, SUBMITTED, APPROVED, REJECTED, REVERTED, CLOSED } enum ValidationStatus { NOT_EXISTS, PENDING, LOCKED, APPROVED, REJECTED, REVERTED } struct Application { bytes32 id; address pgg; address applicant; address operator; uint256 spaceTokenId; uint256 createdAt; Details details; Rewards rewards; Currency currency; ApplicationStatus status; bytes32[] assignedOracleTypes; mapping(bytes32 => uint256) assignedRewards; mapping(bytes32 => bool) oracleTypeRewardPaidOut; mapping(bytes32 => string) oracleTypeMessages; mapping(bytes32 => address) oracleTypeAddresses; mapping(address => bytes32) addressOracleTypes; mapping(bytes32 => ValidationStatus) validationStatus; } struct Rewards { uint256 totalPaidFee; uint256 oraclesReward; uint256 galtProtocolFee; uint256 latestCommittedFee; bool galtProtocolFeePaidOut; } struct Details { bytes32 credentialsHash; bytes32 ledgerIdentifier; string description; int256 level; uint256 area; ISpaceGeoDataRegistry.AreaSource areaSource; uint256[] contour; int256[] heights; } mapping(bytes32 => Application) internal applications; constructor () public {} function initialize( GaltGlobalRegistry _ggr ) public isInitializer { ggr = _ggr; } modifier onlyApplicant(bytes32 _aId) { Application storage a = applications[_aId]; require( a.applicant == msg.sender || getApplicationOperator(_aId) == msg.sender, "Applicant invalid"); _; } modifier onlyOracleOfApplication(bytes32 _aId) { Application storage a = applications[_aId]; require(a.addressOracleTypes[msg.sender] != 0x0, "Not valid oracle"); _; } function feeCalculator(address _pgg) public view returns (IPropertyManagerFeeCalculator) { return IPropertyManagerFeeCalculator(address(uint160(uint256(pggConfigValue(_pgg, CONFIG_FEE_CALCULATOR))))); } function getOracleTypeShareKey(bytes32 _oracleType) public pure returns (bytes32) { return keccak256(abi.encode(CONFIG_PREFIX, "share", _oracleType)); } function paymentMethod(address _pgg) public view returns (PaymentMethod) { return PaymentMethod(uint256(pggConfigValue(_pgg, CONFIG_PAYMENT_METHOD))); } function approveOperator(bytes32 _aId, address _to) external { Application storage a = applications[_aId]; require( msg.sender == a.applicant || (a.status == ApplicationStatus.REJECTED && a.addressOracleTypes[msg.sender] != 0x0), "Unable to approve" ); require(_to != a.applicant, "Unable to approve to the same account"); a.operator = _to; } function submit( address _pgg, uint256[] calldata _contour, int256[] calldata _heights, int256 _level, uint256 _customArea, bytes32 _credentialsHash, bytes32 _ledgerIdentifier, string calldata _description, uint256 _submissionFeeInGalt ) external payable returns (bytes32) { require( _contour.length >= 3 && _contour.length <= 50, "Number of contour elements should be between 3 and 50" ); pggRegistry().requireValidPgg(_pgg); bytes32 _id = keccak256( abi.encodePacked( _pgg, _contour, _credentialsHash, msg.sender, applicationsArray.length ) ); Application storage a = applications[_id]; require(a.status == ApplicationStatus.NOT_EXISTS, "Application already exists"); if (_customArea == 0) { a.details.areaSource = ISpaceGeoDataRegistry.AreaSource.CONTRACT; a.details.area = IGeodesic(ggr.getGeodesicAddress()).calculateContourArea(_contour); } else { a.details.area = _customArea; // Default a.areaSource is AreaSource.USER_INPUT } // GALT if (_submissionFeeInGalt > 0) { requireValidPaymentType(_pgg, PaymentType.GALT); require(msg.value == 0, "Could not accept both ETH and GALT"); require(_submissionFeeInGalt >= getSubmissionFeeByArea(_pgg, Currency.GALT, a.details.area), "Incorrect fee passed in"); require(ggr.getGaltToken().allowance(msg.sender, address(this)) >= _submissionFeeInGalt, "Insufficient allowance"); ggr.getGaltToken().transferFrom(msg.sender, address(this), _submissionFeeInGalt); a.rewards.totalPaidFee = _submissionFeeInGalt; a.currency = Currency.GALT; // ETH } else { requireValidPaymentType(_pgg, PaymentType.ETH); a.rewards.totalPaidFee = msg.value; // Default a.currency is Currency.ETH require( msg.value >= getSubmissionFeeByArea(_pgg, Currency.ETH, a.details.area), "Incorrect msg.value passed in"); } a.status = ApplicationStatus.SUBMITTED; a.id = _id; a.pgg = _pgg; a.applicant = msg.sender; a.createdAt = block.timestamp; calculateAndStoreFee(a, a.rewards.totalPaidFee); a.details.ledgerIdentifier = _ledgerIdentifier; a.details.description = _description; a.details.credentialsHash = _credentialsHash; a.details.level = _level; a.details.contour = _contour; a.details.heights = _heights; applicationsArray.push(_id); applicationsByApplicant[msg.sender].push(_id); emit NewApplication(msg.sender, _id); emit ApplicationStatusChanged(_id, ApplicationStatus.SUBMITTED); assignRequiredOracleTypesAndRewards(applications[_id]); return _id; } /** * @dev Resubmit application after it was reverted * * @param _aId application id * @param _newCredentialsHash keccak256 of user credentials * @param _newLedgerIdentifier of a plot * @param _newDescription of a plot * @param _newContour array, empty if not changed * @param _newHeights array, empty if not changed * @param _newLevel int * @param _newCustomArea int * @param _resubmissionFeeInGalt or 0 if paid by ETH */ function resubmit( bytes32 _aId, bytes32 _newCredentialsHash, bytes32 _newLedgerIdentifier, string calldata _newDescription, uint256[] calldata _newContour, int256[] calldata _newHeights, int256 _newLevel, uint256 _newCustomArea, uint256 _resubmissionFeeInGalt ) external payable { Application storage a = applications[_aId]; Details storage d = a.details; require( a.applicant == msg.sender || getApplicationOperator(_aId) == msg.sender, "Applicant invalid"); require( a.status == ApplicationStatus.REVERTED, "Application status should be REVERTED"); checkResubmissionPayment(a, _resubmissionFeeInGalt, _newContour); if (_newCustomArea == 0) { d.areaSource = ISpaceGeoDataRegistry.AreaSource.CONTRACT; d.area = IGeodesic(ggr.getGeodesicAddress()).calculateContourArea(_newContour); } else { d.area = _newCustomArea; d.areaSource = ISpaceGeoDataRegistry.AreaSource.USER_INPUT; } d.level = _newLevel; d.heights = _newHeights; d.contour = _newContour; d.description = _newDescription; d.ledgerIdentifier = _newLedgerIdentifier; d.credentialsHash = _newCredentialsHash; assignLockedStatus(_aId); changeApplicationStatus(a, ApplicationStatus.SUBMITTED); } function assignLockedStatus(bytes32 _aId) internal { for (uint256 i = 0; i < applications[_aId].assignedOracleTypes.length; i++) { if (applications[_aId].validationStatus[applications[_aId].assignedOracleTypes[i]] != ValidationStatus.LOCKED) { changeValidationStatus(applications[_aId], applications[_aId].assignedOracleTypes[i], ValidationStatus.LOCKED); } } } function checkResubmissionPayment( Application storage a, uint256 _resubmissionFeeInGalt, uint256[] memory _newSpaceTokenContour ) internal { Currency currency = a.currency; uint256 fee; if (a.currency == Currency.GALT) { require(msg.value == 0, "ETH payment not expected"); fee = _resubmissionFeeInGalt; } else { require(_resubmissionFeeInGalt == 0, "GALT payment not expected"); fee = msg.value; } uint256 area = IGeodesic(ggr.getGeodesicAddress()).calculateContourArea(_newSpaceTokenContour); uint256 newMinimalFee = getSubmissionFeeByArea(a.pgg, a.currency, area); uint256 alreadyPaid = a.rewards.latestCommittedFee; if (newMinimalFee > alreadyPaid) { uint256 requiredPayment = newMinimalFee.sub(alreadyPaid); require(fee >= requiredPayment, "Incorrect fee passed in"); } a.rewards.latestCommittedFee = alreadyPaid + fee; } // Application can be locked by an oracle type only once. function lock(bytes32 _aId, bytes32 _oracleType) external { Application storage a = applications[_aId]; requireOracleActiveWithAssignedActiveOracleType(a.pgg, msg.sender, _oracleType); require(a.status == ApplicationStatus.SUBMITTED, "Application status should be SUBMITTED"); require(a.oracleTypeAddresses[_oracleType] == address(0), "Oracle is already assigned on this oracle type"); require(a.validationStatus[_oracleType] == ValidationStatus.PENDING, "Can't lock an oracle type not in PENDING status"); a.oracleTypeAddresses[_oracleType] = msg.sender; a.addressOracleTypes[msg.sender] = _oracleType; applicationsByOracle[msg.sender].push(_aId); changeValidationStatus(a, _oracleType, ValidationStatus.LOCKED); } function unlock(bytes32 _aId, bytes32 _oracleType) external onlyUnlocker { Application storage a = applications[_aId]; require(a.status == ApplicationStatus.SUBMITTED, "Application status should be SUBMITTED"); require(a.validationStatus[_oracleType] == ValidationStatus.LOCKED, "Validation status should be LOCKED"); require(a.oracleTypeAddresses[_oracleType] != address(0), "Address should be already set"); a.oracleTypeAddresses[_oracleType] = address(0); changeValidationStatus(a, _oracleType, ValidationStatus.PENDING); } function approve( bytes32 _aId, bytes32 _credentialsHash ) external onlyOracleOfApplication(_aId) { Application storage a = applications[_aId]; require(a.details.credentialsHash == _credentialsHash, "Credentials don't match"); require(a.status == ApplicationStatus.SUBMITTED, "Application status should be SUBMITTED"); bytes32 oracleType = a.addressOracleTypes[msg.sender]; require(a.validationStatus[oracleType] == ValidationStatus.LOCKED, "Application should be locked first"); require(a.oracleTypeAddresses[oracleType] == msg.sender, "Sender not assigned to this application"); requireOracleActiveWithAssignedActiveOracleType(a.pgg, msg.sender, oracleType); changeValidationStatus(a, oracleType, ValidationStatus.APPROVED); uint256 len = a.assignedOracleTypes.length; bool allApproved = true; for (uint256 i = 0; i < len; i++) { if (a.validationStatus[a.assignedOracleTypes[i]] != ValidationStatus.APPROVED) { allApproved = false; } } if (allApproved) { changeApplicationStatus(a, ApplicationStatus.APPROVED); mintToken(a); } } function claimSpaceToken(bytes32 _aId) external onlyApplicant(_aId) { Application storage a = applications[_aId]; require( a.status == ApplicationStatus.APPROVED, "Application status should be APPROVED"); emit ClaimSpaceToken(_aId, a.spaceTokenId); ggr.getSpaceToken().transferFrom(address(this), a.applicant, a.spaceTokenId); } function mintToken(Application storage a) internal { ISpaceGeoDataRegistry spaceGeoData = ISpaceGeoDataRegistry(ggr.getSpaceGeoDataRegistryAddress()); uint256 spaceTokenId = ISpaceToken(ggr.getSpaceTokenAddress()).mint(address(this)); a.spaceTokenId = spaceTokenId; spaceGeoData.setSpaceTokenContour(spaceTokenId, a.details.contour); spaceGeoData.setSpaceTokenHeights(spaceTokenId, a.details.heights); spaceGeoData.setSpaceTokenLevel(spaceTokenId, a.details.level); spaceGeoData.setSpaceTokenArea(spaceTokenId, a.details.area, a.details.areaSource); spaceGeoData.setSpaceTokenInfo(spaceTokenId, a.details.ledgerIdentifier, a.details.description); emit NewSpaceToken(a.applicant, spaceTokenId, a.id); } function reject( bytes32 _aId, string calldata _message ) external onlyOracleOfApplication(_aId) { Application storage a = applications[_aId]; bytes32 oracleType = a.addressOracleTypes[msg.sender]; requireOracleActiveWithAssignedActiveOracleType(a.pgg, msg.sender, oracleType); // TODO: merge into the contract NewPropertyManagerLib.rejectApplicationHelper(a, _message); changeValidationStatus(a, a.addressOracleTypes[msg.sender], ValidationStatus.REJECTED); changeApplicationStatus(a, ApplicationStatus.REJECTED); } function revert( bytes32 _aId, string calldata _message ) external onlyOracleOfApplication(_aId) { Application storage a = applications[_aId]; bytes32 senderOracleType = a.addressOracleTypes[msg.sender]; uint256 len = a.assignedOracleTypes.length; require(a.status == ApplicationStatus.SUBMITTED, "Application status should be SUBMITTED"); requireOracleActiveWithAssignedActiveOracleType(a.pgg, msg.sender, senderOracleType); require(a.validationStatus[senderOracleType] == ValidationStatus.LOCKED, "Application should be locked first"); for (uint256 i = 0; i < len; i++) { if (a.validationStatus[a.assignedOracleTypes[i]] == ValidationStatus.PENDING) { revert("All oracle types should lock the application first"); } } a.oracleTypeMessages[senderOracleType] = _message; changeValidationStatus(a, senderOracleType, ValidationStatus.REVERTED); changeApplicationStatus(a, ApplicationStatus.REVERTED); } function close(bytes32 _aId) external onlyApplicant(_aId) { Application storage a = applications[_aId]; require( a.status == ApplicationStatus.REVERTED, "Application status should be REVERTED"); changeApplicationStatus(a, ApplicationStatus.CLOSED); } function claimOracleReward( bytes32 _aId ) external onlyOracleOfApplication(_aId) { Application storage a = applications[_aId]; bytes32 senderOracleType = a.addressOracleTypes[msg.sender]; uint256 reward = a.assignedRewards[senderOracleType]; /* solium-disable-next-line */ require( a.status == ApplicationStatus.APPROVED || a.status == ApplicationStatus.REJECTED || a.status == ApplicationStatus.CLOSED, "Application status should be APPROVED, REJECTED or CLOSED"); requireOracleActiveWithAssignedActiveOracleType(a.pgg, msg.sender, senderOracleType); require(reward > 0, "Reward is 0"); require(a.oracleTypeRewardPaidOut[senderOracleType] == false, "Reward is already paid"); a.oracleTypeRewardPaidOut[senderOracleType] = true; _assignGaltProtocolFee(a); if (a.currency == Currency.ETH) { msg.sender.transfer(reward); } else if (a.currency == Currency.GALT) { ggr.getGaltToken().transfer(msg.sender, reward); } emit OracleRewardClaim(_aId, msg.sender); } function _assignGaltProtocolFee(Application storage _a) internal { if (_a.rewards.galtProtocolFeePaidOut == false) { if (_a.currency == Currency.ETH) { protocolFeesEth = protocolFeesEth.add(_a.rewards.galtProtocolFee); } else if (_a.currency == Currency.GALT) { protocolFeesGalt = protocolFeesGalt.add(_a.rewards.galtProtocolFee); } _a.rewards.galtProtocolFeePaidOut = true; emit GaltProtocolFeeAssigned(_a.id); } } function calculateAndStoreFee( Application storage _a, uint256 _fee ) internal { uint256 share; (uint256 ethFee, uint256 galtFee) = getProtocolShares(); if (_a.currency == Currency.ETH) { share = ethFee; } else { share = galtFee; } assert(share > 0); assert(share <= 100); uint256 galtProtocolFee = share.mul(_fee).div(100); uint256 oraclesReward = _fee.sub(galtProtocolFee); assert(oraclesReward.add(galtProtocolFee) == _fee); _a.rewards.oraclesReward = oraclesReward; _a.rewards.galtProtocolFee = galtProtocolFee; _a.rewards.latestCommittedFee = _fee; } function assignRequiredOracleTypesAndRewards(Application storage a) internal { assert(a.rewards.oraclesReward > 0); uint256 totalReward = 0; a.assignedOracleTypes = [PM_SURVEYOR_ORACLE_TYPE, PM_LAWYER_ORACLE_TYPE]; uint256 surveyorShare = oracleTypeShare(a.pgg, PM_SURVEYOR_ORACLE_TYPE); uint256 lawyerShare = oracleTypeShare(a.pgg, PM_LAWYER_ORACLE_TYPE); uint256[2] memory shares = [surveyorShare, lawyerShare]; require(surveyorShare + lawyerShare == 100, "PM shares invalid setup"); uint256 len = a.assignedOracleTypes.length; for (uint256 i = 0; i < len; i++) { bytes32 oracleType = a.assignedOracleTypes[i]; uint256 rewardShare = a .rewards .oraclesReward .mul(shares[i]) .div(100); a.assignedRewards[oracleType] = rewardShare; changeValidationStatus(a, oracleType, ValidationStatus.PENDING); totalReward = totalReward.add(rewardShare); } assert(totalReward <= a.rewards.oraclesReward); uint256 diff = a.rewards.oraclesReward - totalReward; a.assignedRewards[a.assignedOracleTypes[0]] = a.assignedRewards[a.assignedOracleTypes[0]].add(diff); } function changeValidationStatus( Application storage _a, bytes32 _oracleType, ValidationStatus _status ) internal { emit ValidationStatusChanged(_a.id, _oracleType, _status); _a.validationStatus[_oracleType] = _status; } // NOTICE: the application should already persist in storage function changeApplicationStatus( Application storage _a, ApplicationStatus _status ) internal { emit ApplicationStatusChanged(_a.id, _status); _a.status = _status; } function isCredentialsHashValid( bytes32 _id, bytes32 _hash ) external view returns (bool) { return (_hash == applications[_id].details.credentialsHash); } /** * @dev Get common application details */ function getApplication( bytes32 _id ) external view returns ( uint256 createdAt, address applicant, address pgg, uint256 spaceTokenId, ApplicationStatus status, Currency currency, bytes32[] memory assignedOracleTypes ) { require(applications[_id].status != ApplicationStatus.NOT_EXISTS, "Application doesn't exist"); Application storage m = applications[_id]; return ( m.createdAt, m.applicant, m.pgg, m.spaceTokenId, m.status, m.currency, m.assignedOracleTypes ); } /** * @dev Get application rewards-related information */ function getApplicationRewards( bytes32 _id ) external view returns ( ApplicationStatus status, Currency currency, uint256 oraclesReward, uint256 galtProtocolFee, uint256 latestCommittedFee, bool galtProtocolFeePaidOut ) { require(applications[_id].status != ApplicationStatus.NOT_EXISTS, "Application doesn't exist"); Application storage m = applications[_id]; return ( m.status, m.currency, m.rewards.oraclesReward, m.rewards.galtProtocolFee, m.rewards.latestCommittedFee, m.rewards.galtProtocolFeePaidOut ); } /** * @dev Get application details */ function getApplicationDetails( bytes32 _id ) external view returns ( bytes32 credentialsHash, bytes32 ledgerIdentifier, int256 level, uint256 area, ISpaceGeoDataRegistry.AreaSource areaSource, uint256[] memory contour, string memory description, int256[] memory heights ) { require(applications[_id].status != ApplicationStatus.NOT_EXISTS, "Application doesn't exist"); Application storage m = applications[_id]; return ( m.details.credentialsHash, m.details.ledgerIdentifier, m.details.level, m.details.area, m.details.areaSource, m.details.contour, m.details.description, m.details.heights ); } function getApplicationOperator(bytes32 _aId) public view returns (address) { return applications[_aId].operator; } /** * @dev A minimum fee to pass in to #submitApplication() method either in GALT or in ETH */ function getSubmissionFeeByArea(address _pgg, Currency _currency, uint256 _area) public view returns (uint256) { if (_currency == Currency.GALT) { return feeCalculator(_pgg).calculateGaltFee(_area); } else { return feeCalculator(_pgg).calculateEthFee(_area); } } /** * @dev Fee to pass in to #resubmitApplication(). */ function getResubmissionFeeByArea(bytes32 _aId, uint256 _area) external view returns (uint256) { Application storage a = applications[_aId]; uint256 newTotalFee = getSubmissionFeeByArea(a.pgg, a.currency, _area); uint256 latest = a.rewards.latestCommittedFee; if (newTotalFee <= latest) { return 0; } else { return newTotalFee - latest; } } function getApplicationOracle( bytes32 _aId, bytes32 _oracleType ) external view returns ( address oracle, uint256 reward, bool rewardPaidOut, ValidationStatus status, string memory message ) { return ( applications[_aId].oracleTypeAddresses[_oracleType], applications[_aId].assignedRewards[_oracleType], applications[_aId].oracleTypeRewardPaidOut[_oracleType], applications[_aId].validationStatus[_oracleType], applications[_aId].oracleTypeMessages[_oracleType] ); } }
Get application rewards-related information/
function getApplicationRewards( bytes32 _id ) external view returns ( ApplicationStatus status, Currency currency, uint256 oraclesReward, uint256 galtProtocolFee, uint256 latestCommittedFee, bool galtProtocolFeePaidOut ) { require(applications[_id].status != ApplicationStatus.NOT_EXISTS, "Application doesn't exist"); Application storage m = applications[_id]; return ( m.status, m.currency, m.rewards.oraclesReward, m.rewards.galtProtocolFee, m.rewards.latestCommittedFee, m.rewards.galtProtocolFeePaidOut ); }
1,069,377
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) { 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&#39;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. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract BattleBase is Ownable { using SafeMath for uint256; /***********************************************************************************/ /* EVENTS /***********************************************************************************/ /** * History sequence will be represented by uint256, in other words the max round is 256 (rounds more than this will decide on hp left or draw) * 1 is challenger attack * 2 is defender attack * 3 is challenger attack with critical * 4 is defender attack with critical */ event BattleHistory( uint256 historyId, uint8 winner, // 0 - challenger; 1 - defender; 2 - draw; uint64 battleTime, uint256 sequence, uint256 blockNumber, uint256 tokensGained); event BattleHistoryChallenger( uint256 historyId, uint256 cardId, uint8 element, uint16 level, uint32 attack, uint32 defense, uint32 hp, uint32 speed, uint32 criticalRate, uint256 rank); event BattleHistoryDefender( uint256 historyId, uint256 cardId, uint8 element, uint16 level, uint32 attack, uint32 defense, uint32 hp, uint32 speed, uint16 criticalRate, uint256 rank); event RejectChallenge( uint256 challengerId, uint256 defenderId, uint256 defenderRank, uint8 rejectCode, uint256 blockNumber); event HashUpdated( uint256 cardId, uint256 cardHash); event LevelUp(uint256 cardId); event CardCreated(address owner, uint256 cardId); /***********************************************************************************/ /* CONST DATA /***********************************************************************************/ uint32[] expToNextLevelArr = [0,103,103,207,207,207,414,414,414,414,724,724,724,828,828,931,931,1035,1035,1138,1138,1242,1242,1345,1345,1449,1449,1552,1552,1656,1656,1759,1759,1863,1863,1966,1966,2070,2070,2173,2173,2173,2277,2277,2380,2380,2484,2484,2587,2587,2691,2691,2794,2794,2898,2898,3001,3001,3105,3105,3208,3208,3312,3312,3415,3415,3519,3519,3622,3622,3622,3726,3726,3829,3829,3933,3933,4036,4036,4140,4140,4243,4243,4347,4347,4450,4450,4554,4554,4657,4657,4761,4761,4864,4864,4968,4968,5071,5071,5175]; uint32[] activeWinExp = [10,11,14,19,26,35,46,59,74,91,100,103,108,116,125,135,146,158,171,185,200,215,231,248,265,283,302,321,341,361,382]; /***********************************************************************************/ /* DATA VARIABLES /***********************************************************************************/ //Card structure that holds all information for battle struct Card { uint8 element; // 1 - fire; 2 - water; 3 - wood; 8 - light; 9 - dark; uint16 level; //"unlimited" level bound to uint16 Max level is 65535 uint32 attack; uint32 defense; uint32 hp; uint32 speed; uint16 criticalRate; //max 8000 uint32 flexiGems; uint256 cardHash; uint32 currentExp; uint32 expToNextLevel; uint64 createdDatetime; uint256 rank; //rank is n-1 (need to add 1 for display); //uint8 passiveSkill; //TBC } // Mapping from tokenId to Card Struct mapping (uint256 => Card) public cards; uint256[] ranking; //stores the token id according to array position starts from 0 (rank 1) // Mapping from rank to amount held in that rank (challenge tokens) mapping (uint256 => uint256) public rankTokens; uint8 public currentElement = 0; //start with 0 as +1 will become fire uint256 public historyId = 0; /***********************************************************************************/ /* CONFIGURATIONS /***********************************************************************************/ /// @dev The address of the HogSmashToken HogSmashToken public hogsmashToken; /// @dev The address of the Marketplace Marketplace public marketplace; // Challenge fee changes on ranking difference uint256 public challengeFee; // Upgrade fee uint256 public upgradeFee; // Avatar fee uint256 public avatarFee; // Referrer fee in % (x10000) uint256 public referrerFee; // Developer Cut in % (x10000) uint256 public developerCut; uint256 internal totalDeveloperCut; // Price for each card draw (in wei) uint256 public cardDrawPrice; // Gems provided for upgrade every level up uint8 public upgradeGems; // // Gems provided for upgrade every 10 level up uint8 public upgradeGemsSpecial; // 1 Gem to attack conversion uint16 public gemAttackConversion; // 1 Gem to defense conversion uint16 public gemDefenseConversion; // 1 Gem to hp conversion uint16 public gemHpConversion; // 1 Gem to speed conversion uint16 public gemSpeedConversion; // 1 Gem to critical rate conversion divided by 100, eg 25 = 0.25 uint16 public gemCriticalRateConversion; //% to get a gold card, 0 to 100 uint8 public goldPercentage; //% to get a silver card, 0 to 100 uint8 public silverPercentage; //Range of event card number 1-99999999 uint32 public eventCardRangeMin; //Range of event card number 1-99999999 uint32 public eventCardRangeMax; // Maximum rounds of battle, cannot exceed 128 uint8 public maxBattleRounds; // // Record how much tokens are held as rank tokens uint256 internal totalRankTokens; // Flag for start fighting bool internal battleStart; //Flag for starter pack sale bool internal starterPackOnSale; uint256 public starterPackPrice; //price of starter pack uint16 public starterPackCardLevel; //card level from starter pack /***********************************************************************************/ /* ADMIN FUNCTIONS FOR SETTING CONFIGS /***********************************************************************************/ /// @dev Sets the reference to the marketplace. /// @param _address - Address of marketplace. function setMarketplaceAddress(address _address) external onlyOwner { Marketplace candidateContract = Marketplace(_address); require(candidateContract.isMarketplace(),"needs to be marketplace"); // Set the new contract address marketplace = candidateContract; } /** * @dev set upgrade gems for each level up and each 10 level up * @param _upgradeGems upgrade gems for normal levels * @param _upgradeGemsSpecial upgrade gems for every n levels * @param _gemAttackConversion gem to attack conversion * @param _gemDefenseConversion gem to defense conversion * @param _gemHpConversion gem to hp conversion * @param _gemSpeedConversion gem to speed conversion * @param _gemCriticalRateConversion gem to critical rate conversion * @param _goldPercentage percentage to get gold card * @param _silverPercentage percentage to get silver card * @param _eventCardRangeMin event card hash range start (inclusive) * @param _eventCardRangeMax event card hash range end (inclusive) * @param _newMaxBattleRounds maximum battle rounds */ function setSettingValues( uint8 _upgradeGems, uint8 _upgradeGemsSpecial, uint16 _gemAttackConversion, uint16 _gemDefenseConversion, uint16 _gemHpConversion, uint16 _gemSpeedConversion, uint16 _gemCriticalRateConversion, uint8 _goldPercentage, uint8 _silverPercentage, uint32 _eventCardRangeMin, uint32 _eventCardRangeMax, uint8 _newMaxBattleRounds) external onlyOwner { require(_eventCardRangeMax >= _eventCardRangeMin, "range max must be larger or equals range min" ); require(_eventCardRangeMax<100000000, "range max cannot exceed 99999999"); require((_newMaxBattleRounds <= 128) && (_newMaxBattleRounds >0), "battle rounds must be between 0 and 128"); upgradeGems = _upgradeGems; upgradeGemsSpecial = _upgradeGemsSpecial; gemAttackConversion = _gemAttackConversion; gemDefenseConversion = _gemDefenseConversion; gemHpConversion = _gemHpConversion; gemSpeedConversion = _gemSpeedConversion; gemCriticalRateConversion = _gemCriticalRateConversion; goldPercentage = _goldPercentage; silverPercentage = _silverPercentage; eventCardRangeMin = _eventCardRangeMin; eventCardRangeMax = _eventCardRangeMax; maxBattleRounds = _newMaxBattleRounds; } // @dev function to allow contract owner to change the price (in wei) per card draw function setStarterPack(uint256 _newStarterPackPrice, uint16 _newStarterPackCardLevel) external onlyOwner { require(_newStarterPackCardLevel<=20, "starter pack level cannot exceed 20"); //starter pack level cannot exceed 20 starterPackPrice = _newStarterPackPrice; starterPackCardLevel = _newStarterPackCardLevel; } // @dev function to allow contract owner to enable/disable starter pack sale function setStarterPackOnSale(bool _newStarterPackOnSale) external onlyOwner { starterPackOnSale = _newStarterPackOnSale; } // @dev function to allow contract owner to start/stop the battle function setBattleStart(bool _newBattleStart) external onlyOwner { battleStart = _newBattleStart; } // @dev function to allow contract owner to change the price (in wei) per card draw function setCardDrawPrice(uint256 _newCardDrawPrice) external onlyOwner { cardDrawPrice = _newCardDrawPrice; } // @dev function to allow contract owner to change the referrer fee (in %, eg 3.75% is 375) function setReferrerFee(uint256 _newReferrerFee) external onlyOwner { referrerFee = _newReferrerFee; } // @dev function to allow contract owner to change the challenge fee (in wei) function setChallengeFee(uint256 _newChallengeFee) external onlyOwner { challengeFee = _newChallengeFee; } // @dev function to allow contract owner to change the upgrade fee (in wei) function setUpgradeFee(uint256 _newUpgradeFee) external onlyOwner { upgradeFee = _newUpgradeFee; } // @dev function to allow contract owner to change the avatar fee (in wei) function setAvatarFee(uint256 _newAvatarFee) external onlyOwner { avatarFee = _newAvatarFee; } // @dev function to allow contract owner to change the developer cut (%) divide by 100 function setDeveloperCut(uint256 _newDeveloperCut) external onlyOwner { developerCut = _newDeveloperCut; } function getTotalDeveloperCut() external view onlyOwner returns (uint256) { return totalDeveloperCut; } function getTotalRankTokens() external view returns (uint256) { return totalRankTokens; } /***********************************************************************************/ /* GET SETTINGS FUNCTION /***********************************************************************************/ /** * @dev get upgrade gems and conversion ratios of each field * @return _upgradeGems upgrade gems for normal levels * @return _upgradeGemsSpecial upgrade gems for every n levels * @return _gemAttackConversion gem to attack conversion * @return _gemDefenseConversion gem to defense conversion * @return _gemHpConversion gem to hp conversion * @return _gemSpeedConversion gem to speed conversion * @return _gemCriticalRateConversion gem to critical rate conversion */ function getSettingValues() external view returns( uint8 _upgradeGems, uint8 _upgradeGemsSpecial, uint16 _gemAttackConversion, uint16 _gemDefenseConversion, uint16 _gemHpConversion, uint16 _gemSpeedConversion, uint16 _gemCriticalRateConversion, uint8 _maxBattleRounds) { _upgradeGems = uint8(upgradeGems); _upgradeGemsSpecial = uint8(upgradeGemsSpecial); _gemAttackConversion = uint16(gemAttackConversion); _gemDefenseConversion = uint16(gemDefenseConversion); _gemHpConversion = uint16(gemHpConversion); _gemSpeedConversion = uint16(gemSpeedConversion); _gemCriticalRateConversion = uint16(gemCriticalRateConversion); _maxBattleRounds = uint8(maxBattleRounds); } } /***********************************************************************************/ /* RANDOM GENERATOR /***********************************************************************************/ contract Random { uint private pSeed = block.number; function getRandom() internal returns(uint256) { return (pSeed = uint(keccak256(abi.encodePacked(pSeed, blockhash(block.number - 1), blockhash(block.number - 3), blockhash(block.number - 5), blockhash(block.number - 7)) ))); } } /***********************************************************************************/ /* CORE BATTLE CONTRACT /***********************************************************************************/ /** * Omits fallback to prevent accidentally sending ether to this contract */ contract Battle is BattleBase, Random, Pausable { /***********************************************************************************/ /* CONSTRUCTOR /***********************************************************************************/ // @dev Contructor for Battle Contract constructor(address _tokenAddress) public { HogSmashToken candidateContract = HogSmashToken(_tokenAddress); // Set the new contract address hogsmashToken = candidateContract; starterPackPrice = 30000000000000000; starterPackCardLevel = 5; starterPackOnSale = true; // start by selling starter pack challengeFee = 10000000000000000; upgradeFee = 10000000000000000; avatarFee = 50000000000000000; developerCut = 375; referrerFee = 2000; cardDrawPrice = 15000000000000000; battleStart = true; paused = false; //default contract paused totalDeveloperCut = 0; //init to 0 } /***********************************************************************************/ /* MODIFIER /***********************************************************************************/ /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(hogsmashToken.ownerOf(_tokenId) == msg.sender, "must be owner of token"); _; } /***********************************************************************************/ /* GAME FUNCTIONS /***********************************************************************************/ /** * @dev External function for getting info of card * @param _id card id of target query card * @return information of the card */ function getCard(uint256 _id) external view returns ( uint256 cardId, address owner, uint8 element, uint16 level, uint32[] stats, uint32 currentExp, uint32 expToNextLevel, uint256 cardHash, uint64 createdDatetime, uint256 rank ) { cardId = _id; owner = hogsmashToken.ownerOf(_id); Card storage card = cards[_id]; uint32[] memory tempStats = new uint32[](6); element = uint8(card.element); level = uint16(card.level); tempStats[0] = uint32(card.attack); tempStats[1] = uint32(card.defense); tempStats[2] = uint32(card.hp); tempStats[3] = uint32(card.speed); tempStats[4] = uint16(card.criticalRate); tempStats[5] = uint32(card.flexiGems); stats = tempStats; currentExp = uint32(card.currentExp); expToNextLevel = uint32(card.expToNextLevel); cardHash = uint256(card.cardHash); createdDatetime = uint64(card.createdDatetime); rank = uint256(card.rank); } /** * @dev External function for querying card Id at rank (zero based) * @param _rank zero based rank of the card * @return id of the card at the rank */ function getCardIdByRank(uint256 _rank) external view returns(uint256 cardId) { return ranking[_rank]; } /** * @dev External function for drafting new card * @return uint of cardId */ function draftNewCard() external payable whenNotPaused returns (uint256) { require(msg.value == cardDrawPrice, "fee must be equal to draw price"); //make sure the fee is enough for drafting a new card` require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice); return _createCard(msg.sender, 1); //level 1 cards } /** * @dev External function for drafting new card * @return uint of cardId */ function draftNewCardWithReferrer(address referrer) external payable whenNotPaused returns (uint256 cardId) { require(msg.value == cardDrawPrice, "fee must be equal to draw price"); //make sure the fee is enough for drafting a new card` require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale cardId = _createCard(msg.sender, 1); //level 1 cards if ((referrer != address(0)) && (referrerFee!=0) && (referrer!=msg.sender) && (hogsmashToken.balanceOf(referrer)>0)) { uint256 referrerCut = msg.value.mul(referrerFee)/10000; require(referrerCut<=msg.value, "referre cut cannot be larger than fee"); referrer.transfer(referrerCut); totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice.sub(referrerCut)); } else { totalDeveloperCut = totalDeveloperCut.add(cardDrawPrice); } } /** * @dev External function for leveling up * @param _id card id of target query card * @param _attackLevelUp gems allocated to each attribute for upgrade * @param _defenseLevelUp gems allocated to each attribute for upgrade * @param _hpLevelUp gems allocated to each attribute for upgrade * @param _speedLevelUp gems allocated to each attribute for upgrade * @param _criticalRateLevelUp gems allocated to each attribute for upgrade * @param _flexiGemsLevelUp are gems allocated to each attribute for upgrade */ function levelUp( uint256 _id, uint16 _attackLevelUp, uint16 _defenseLevelUp, uint16 _hpLevelUp, uint16 _speedLevelUp, uint16 _criticalRateLevelUp, uint16 _flexiGemsLevelUp) external payable whenNotPaused onlyOwnerOf(_id) { require( _attackLevelUp >= 0 && _defenseLevelUp >= 0 && _hpLevelUp >= 0 && _speedLevelUp >= 0 && _criticalRateLevelUp >= 0 && _flexiGemsLevelUp >= 0, "level up attributes must be more than 0" ); //make sure all upgrade attributes will not be negative require(msg.value == upgradeFee, "fee must be equals to upgrade price"); //make sure the fee is enough for upgrade Card storage card = cards[_id]; require(card.currentExp==card.expToNextLevel, "exp is not max yet for level up"); //reject if currentexp not maxed out require(card.level < 65535, "card level maximum has reached"); //make sure level is not maxed out, although not likely require((card.criticalRate + (_criticalRateLevelUp * gemCriticalRateConversion))<=7000, "critical rate max of 70 has reached"); //make sure criticalrate is not upgraded when it reaches 70 to prevent waste uint totalInputGems = _attackLevelUp + _defenseLevelUp + _hpLevelUp; totalInputGems += _speedLevelUp + _criticalRateLevelUp + _flexiGemsLevelUp; uint16 numOfSpecials = 0; //Cater for initial high level cards but have not leveled up before if ((card.level > 1) && (card.attack==1) && (card.defense==1) && (card.hp==3) && (card.speed==1) && (card.criticalRate==25) && (card.flexiGems==1)) { numOfSpecials = (card.level+1)/5; //auto floor to indicate how many Ns for upgradeGemsSpecial; cardlevel +1 is the new level uint totalGems = (numOfSpecials * upgradeGemsSpecial) + (((card.level) - numOfSpecials) * upgradeGems); require(totalInputGems==totalGems, "upgrade gems not used up"); //must use up all gems when upgrade } else { if (((card.level+1)%5)==0) { //special gem every 5 levels require(totalInputGems==upgradeGemsSpecial, "upgrade gems not used up"); //must use up all gems when upgrade numOfSpecials = 1; } else { require(totalInputGems==upgradeGems, "upgrade gems not used up"); //must use up all gems when upgrade } } totalDeveloperCut = totalDeveloperCut.add(upgradeFee); //start level up process _upgradeLevel(_id, _attackLevelUp, _defenseLevelUp, _hpLevelUp, _speedLevelUp, _criticalRateLevelUp, _flexiGemsLevelUp, numOfSpecials); emit LevelUp(_id); } function _upgradeLevel( uint256 _id, uint16 _attackLevelUp, uint16 _defenseLevelUp, uint16 _hpLevelUp, uint16 _speedLevelUp, uint16 _criticalRateLevelUp, uint16 _flexiGemsLevelUp, uint16 numOfSpecials) private { Card storage card = cards[_id]; uint16[] memory extraStats = new uint16[](5); //attack, defense, hp, speed, flexigem if (numOfSpecials>0) { //special gem every 5 levels if (card.cardHash%100 >= 70) { //6* or 7* cards uint cardType = (uint(card.cardHash/10000000000))%100; //0-99 if (cardType < 20) { extraStats[0]+=numOfSpecials; } else if (cardType < 40) { extraStats[1]+=numOfSpecials; } else if (cardType < 60) { extraStats[2]+=numOfSpecials; } else if (cardType < 80) { extraStats[3]+=numOfSpecials; } else { extraStats[4]+=numOfSpecials; } if (card.cardHash%100 >=90) { //7* cards uint cardTypeInner = cardType%10; //0-9 if (cardTypeInner < 2) { extraStats[0]+=numOfSpecials; } else if (cardTypeInner < 4) { extraStats[1]+=numOfSpecials; } else if (cardTypeInner < 6) { extraStats[2]+=numOfSpecials; } else if (cardTypeInner < 8) { extraStats[3]+=numOfSpecials; } else { extraStats[4]+=numOfSpecials; } } } } card.attack += (_attackLevelUp + extraStats[0]) * gemAttackConversion; card.defense += (_defenseLevelUp + extraStats[1]) * gemDefenseConversion; card.hp += (_hpLevelUp + extraStats[2]) * gemHpConversion; card.speed += (_speedLevelUp + extraStats[3]) * gemSpeedConversion; card.criticalRate += uint16(_criticalRateLevelUp * gemCriticalRateConversion); card.flexiGems += _flexiGemsLevelUp + extraStats[4]; // turn Gem into FlexiGem card.level += 1; //level + 1 card.currentExp = 0; //reset exp //card.expToNextLevel = card.level*100 + max(0,card.level-8) * (1045/1000)**card.level; uint256 tempExpLevel = card.level; if (tempExpLevel > expToNextLevelArr.length) { tempExpLevel = expToNextLevelArr.length; //cap it at max level exp } card.expToNextLevel = expToNextLevelArr[tempExpLevel]; } function max(uint a, uint b) private pure returns (uint) { return a > b ? a : b; } function challenge( uint256 _challengerCardId, uint32[5] _statUp, //0-attack, 1-defense, 2-hp, 3-speed, 4-criticalrate uint256 _defenderCardId, uint256 _defenderRank, uint16 _defenderLevel) external payable whenNotPaused onlyOwnerOf(_challengerCardId) { require(battleStart != false, "battle has not started"); //make sure the battle has started require(msg.sender != hogsmashToken.ownerOf(_defenderCardId), "cannot challenge own cards"); //make sure user doesn&#39;t attack his own cards Card storage challenger = cards[_challengerCardId]; require((_statUp[0] + _statUp[1] + _statUp[2] + _statUp[3] + _statUp[4])==challenger.flexiGems, "flexi gems not used up"); //flexi points must be exactly used, not more not less Card storage defender = cards[_defenderCardId]; if (defender.rank != _defenderRank) { emit RejectChallenge(_challengerCardId, _defenderCardId, _defenderRank, 1, uint256(block.number)); (msg.sender).transfer(msg.value); return; } if (defender.level != _defenderLevel) { emit RejectChallenge(_challengerCardId, _defenderCardId, _defenderRank, 2, uint256(block.number)); (msg.sender).transfer(msg.value); return; } uint256 requiredChallengeFee = challengeFee; if (defender.rank <150) { //0-149 rank within 150 requiredChallengeFee = requiredChallengeFee.mul(2); } require(msg.value == requiredChallengeFee, "fee must be equals to challenge price"); //challenge fee to challenge defender uint256 developerFee = 0; if (msg.value > 0) { developerFee = _calculateFee(msg.value); } uint256[] memory stats = new uint256[](14); //challengerattack, challengerdefense, challengerhp, challengerspeed, challengercritical, defendercritical, defenderhp, finalWinner stats[0] = challenger.attack + (_statUp[0] * gemAttackConversion); stats[1] = challenger.defense + (_statUp[1] * gemDefenseConversion); stats[2] = challenger.hp + (_statUp[2] * gemHpConversion); stats[3] = challenger.speed + (_statUp[3] * gemSpeedConversion); stats[4] = challenger.criticalRate + (_statUp[4] * gemCriticalRateConversion); stats[5] = defender.criticalRate; stats[6] = defender.hp; stats[8] = challenger.hp + (_statUp[2] * gemHpConversion); //challenger hp for record purpose stats[9] = challenger.rank; //for looting stats[10] = defender.rank; //for looting stats[11] = 0; //tokensGained stats[12] = _challengerCardId; stats[13] = _defenderCardId; //check challenger critical rate if (stats[4]>7000) { stats[4] = 7000; //hard cap at 70 critical rate } //check defender critical rate if (stats[5]>7000) { stats[5] = 7000; //hard cap at 70 critical rate } // 1 - fire; 2 - water; 3 - wood; 8 - light; 9 - dark; if (((challenger.element-1) == defender.element) || ((challenger.element==1) && (defender.element==3)) || ((challenger.element==8) && (defender.element==9))) { stats[4] += 3000; //30% critical rate increase for challenger if (stats[4]>8000) { stats[4] = 8000; //hard cap at 80 critical rate for element advantage } } if (((defender.element-1) == challenger.element) || ((defender.element==1) && (challenger.element==3)) || ((defender.element==8) && (challenger.element==9))) { stats[5] += 3000; //30% critical rate increase for defender if (stats[5]>8000) { stats[5] = 8000; //hard cap at 80 critical rate for element advantage } } uint256 battleSequence = _simulateBattle(challenger, defender, stats); stats[11] = _transferFees(_challengerCardId, stats, developerFee); emit BattleHistory( historyId, uint8(stats[7]), uint64(now), uint256(battleSequence), uint256(block.number), uint256(stats[11]) ); emit BattleHistoryChallenger( historyId, uint256(_challengerCardId), uint8(challenger.element), uint16(challenger.level), uint32(stats[0]), uint32(stats[1]), uint32(stats[8]), uint32(stats[3]), uint16(stats[4]), //pretty sure trimming down the uint won&#39;t affect the number as max is just 80000 uint256(stats[9]) ); emit BattleHistoryDefender( historyId, uint256(_defenderCardId), uint8(defender.element), uint16(defender.level), uint32(defender.attack), uint32(defender.defense), uint32(defender.hp), uint32(defender.speed), uint16(stats[5]), uint256(stats[10]) ); historyId = historyId.add(1); //add one for next history } function _addBattleSequence(uint8 attackType, uint8 rounds, uint256 battleSequence) private pure returns (uint256) { // Assumed rounds 0-based; attackType is 0xB (B:0,1,2,3), i.e. the last 2 bits is the value with other bits zeros uint256 mask = 0x3; mask = ~(mask << 2*rounds); uint256 newSeq = battleSequence & mask; newSeq = newSeq | (uint256(attackType) << 2*rounds); return newSeq; } function _simulateBattle(Card storage challenger, Card storage defender, uint[] memory stats) private returns (uint256 battleSequence) { bool continueBattle = true; uint8 currentAttacker = 0; //0 challenger, 1 defender uint256 tempAttackStrength; uint8 battleRound = 0; if (!_isChallengerAttackFirst(stats[3], defender.speed)){ currentAttacker = 1; } while (continueBattle) { if (currentAttacker==0) { //challenger attack if (_rollCriticalDice() <= stats[4]){ tempAttackStrength = stats[0] * 2; //critical hit battleSequence = _addBattleSequence(2, battleRound, battleSequence); //move sequence to left and add record } else { tempAttackStrength = stats[0]; //normal hit battleSequence = _addBattleSequence(0, battleRound, battleSequence); //move sequence to left and add record } if (tempAttackStrength <= defender.defense) { tempAttackStrength = 1; //at least deduct 1 hp } else { tempAttackStrength -= defender.defense; } if (stats[6] <= tempAttackStrength) { stats[6] = 0; //do not let it overflow } else { stats[6] -= tempAttackStrength; //defender hp } currentAttacker = 1; //defender turn up next } else if (currentAttacker==1) { //defender attack if (_rollCriticalDice() <= stats[5]){ tempAttackStrength = defender.attack * 2; //critical hit battleSequence = _addBattleSequence(3, battleRound, battleSequence); //move sequence to left and add record } else { tempAttackStrength = defender.attack; //normal hit battleSequence = _addBattleSequence(1, battleRound, battleSequence); //move sequence to left and add record } if (tempAttackStrength <= stats[1]) { tempAttackStrength = 1; //at least deduct 1 hp } else { tempAttackStrength -= stats[1]; } if (stats[2] <= tempAttackStrength) { stats[2] = 0; //do not let it overflow } else { stats[2] -= tempAttackStrength; //challenger hp } currentAttacker = 0; //challenger turn up next } battleRound ++; if ((battleRound>=maxBattleRounds) || (stats[6]<=0) || (stats[2]<=0)){ continueBattle = false; //end battle } } uint32 challengerGainExp = 0; uint32 defenderGainExp = 0; //calculate Exp if (challenger.level == defender.level) { //challenging a same level card challengerGainExp = activeWinExp[10]; } else if (challenger.level > defender.level) { //challenging a lower level card if ((challenger.level - defender.level) >= 11) { challengerGainExp = 1; //defender too weak, grant only 1 exp } else { //challengerGainExp = (((1 + ((defender.level - challenger.level)/10))**2) + (1/10)) * baseExp; challengerGainExp = activeWinExp[10 + defender.level - challenger.level]; //0 - 9 } } else if (challenger.level < defender.level) { //challenging a higher level card //challengerGainExp = ((1 + ((defender.level - challenger.level)/10)**(3/2))) * baseExp; uint256 levelDiff = defender.level - challenger.level; if (levelDiff > 20) { levelDiff = 20; //limit level difference to 20 as max exp gain } challengerGainExp = activeWinExp[10+levelDiff]; } if (stats[2] == stats[6]) { //challenger hp = defender hp stats[7] = 2; //draw //No EXP when draw } else if (stats[2] > stats[6]) { //challenger hp > defender hp stats[7] = 0; //challenger wins if (defender.rank < challenger.rank) { //swap ranks ranking[defender.rank] = stats[12]; //update ranking table position ranking[challenger.rank] = stats[13]; //update ranking table position uint256 tempRank = defender.rank; defender.rank = challenger.rank; //update rank on card challenger.rank = tempRank; //update rank on card } //award Exp //active win challenger.currentExp += challengerGainExp; if (challenger.currentExp > challenger.expToNextLevel) { challenger.currentExp = challenger.expToNextLevel; //cap it at max exp for level up } //passive lose //defenderGainExp = challengerGainExp*35/100*30/100 + (5/10); defenderGainExp = ((challengerGainExp*105/100) + 5)/10; // 30% of 35% + round up if (defenderGainExp <= 0) { defenderGainExp = 1; //at least 1 Exp } defender.currentExp += defenderGainExp; if (defender.currentExp > defender.expToNextLevel) { defender.currentExp = defender.expToNextLevel; //cap it at max exp for level up } } else if (stats[6] > stats[2]) { //defender hp > challenger hp stats[7] = 1; //defender wins //award Exp //active lose uint32 tempChallengerGain = challengerGainExp*35/100; //35% of winning if (tempChallengerGain <= 0) { tempChallengerGain = 1; //at least 1 Exp } challenger.currentExp += tempChallengerGain; //35% of winning if (challenger.currentExp > challenger.expToNextLevel) { challenger.currentExp = challenger.expToNextLevel; //cap it at max exp for level up } //passive win defenderGainExp = challengerGainExp*30/100; if (defenderGainExp <= 0) { defenderGainExp = 1; //at least 1 Exp } defender.currentExp += defenderGainExp; if (defender.currentExp > defender.expToNextLevel) { defender.currentExp = defender.expToNextLevel; //cap it at max exp for level up } } return battleSequence; } function _transferFees(uint256 _challengerCardId, uint[] stats, uint256 developerFee) private returns (uint256 totalGained) { totalDeveloperCut = totalDeveloperCut.add(developerFee); uint256 remainFee = msg.value.sub(developerFee); //minus developer fee totalGained = 0; if (stats[7] == 1) { //challenger loses // put all of challenger fee in rankTokens (minus developerfee of course) rankTokens[stats[10]] = rankTokens[stats[10]].add(remainFee); totalRankTokens = totalRankTokens.add(remainFee); } else { //draw or challenger wins address challengerAddress = hogsmashToken.ownerOf(_challengerCardId); //get address of card owner if (stats[7] == 0) { //challenger wins if (stats[9] > stats[10]) { //challenging a higher ranking defender //1. get tokens from defender rank if defender rank is higher if (rankTokens[stats[10]] > 0) { totalGained = totalGained.add(rankTokens[stats[10]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[10]]); rankTokens[stats[10]] = 0; } //2. get self rank tokens if moved to higher rank if (rankTokens[stats[9]] > 0) { totalGained = totalGained.add(rankTokens[stats[9]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[9]]); rankTokens[stats[9]] = 0; } } else { //challenging a lower ranking defender if (stats[9]<50) { //rank 1-50 gets to get self rank tokens and lower rank (within 150) tokens if win if ((stats[10] < 150) && (rankTokens[stats[10]] > 0)) { // can get defender rank tokens if defender rank within top 150 (0-149) totalGained = totalGained.add(rankTokens[stats[10]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[10]]); rankTokens[stats[10]] = 0; } if ((stats[10] < 150) && (rankTokens[stats[9]] > 0)) { //can get self rank tokens if defender rank within top 150 totalGained = totalGained.add(rankTokens[stats[9]]); totalRankTokens = totalRankTokens.sub(rankTokens[stats[9]]); rankTokens[stats[9]] = 0; } } } challengerAddress.transfer(totalGained.add(remainFee)); //give back challenge fee untouched + total gained } else { //draw challengerAddress.transfer(remainFee); //give back challenge fee untouched } } } function _rollCriticalDice() private returns (uint16 result){ return uint16((getRandom() % 10000) + 1); //get 1 to 10000 } function _isChallengerAttackFirst(uint _challengerSpeed, uint _defenderSpeed ) private returns (bool){ uint8 randResult = uint8((getRandom() % 100) + 1); //get 1 to 100 uint challengerChance = (((_challengerSpeed * 10 ** 3) / (_challengerSpeed + _defenderSpeed))+5) / 10;//round if (randResult <= challengerChance) { return true; } else { return false; } } /// @dev function to buy starter package, with card and tokens directly from contract function buyStarterPack() external payable whenNotPaused returns (uint256){ require(starterPackOnSale==true, "starter pack is not on sale"); require(msg.value==starterPackPrice, "fee must be equals to starter pack price"); require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed totalDeveloperCut = totalDeveloperCut.add(starterPackPrice); hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale return _createCard(msg.sender, starterPackCardLevel); //level n cards } /** * @dev Create card function * @param _to The address that will own the minted card * @param _initLevel The level to start with, usually 1 * @return uint256 ID of the new card */ function _createCard(address _to, uint16 _initLevel) private returns (uint256) { require(_to != address(0), "cannot create card for unknown address"); //check if address is not 0 (the origin address) currentElement+= 1; if (currentElement==4) { currentElement = 8; } if (currentElement == 10) { currentElement = 1; } uint256 tempExpLevel = _initLevel; if (tempExpLevel > expToNextLevelArr.length) { tempExpLevel = expToNextLevelArr.length; //cap it at max level exp } uint32 tempCurrentExp = 0; if (_initLevel>1) { //let exp max out so that user can level up the card according to preference tempCurrentExp = expToNextLevelArr[tempExpLevel]; } uint256 tokenId = hogsmashToken.mint(_to); // use memory as this is a temporary variable, cheaper and will not be stored since cards store all of them Card memory _card = Card({ element: currentElement, // 1 - fire; 2 - water; 3 - wood; 8 - light; 9 - dark; level: _initLevel, // level attack: 1, // attack, defense: 1, // defense, hp: 3, // hp, speed: 1, // speed, criticalRate: 25, // criticalRate flexiGems: 1, // flexiGems, currentExp: tempCurrentExp, // currentExp, expToNextLevel: expToNextLevelArr[tempExpLevel], // expToNextLevel, cardHash: generateHash(), createdDatetime :uint64(now), rank: tokenId // rank }); cards[tokenId] = _card; ranking.push(tokenId); //push to ranking mapping emit CardCreated(msg.sender, tokenId); return tokenId; } function generateHash() private returns (uint256 hash){ hash = uint256((getRandom()%1000000000000)/10000000000); hash = hash.mul(10000000000); uint256 tempHash = ((getRandom()%(eventCardRangeMax-eventCardRangeMin+1))+eventCardRangeMin)*100; hash = hash.add(tempHash); tempHash = getRandom()%100; if (tempHash < goldPercentage) { hash = hash.add(90); } else if (tempHash < (goldPercentage+silverPercentage)) { hash = hash.add(70); } else { hash = hash.add(50); } } /// @dev function to update avatar hash function updateAvatar(uint256 _cardId, uint256 avatarHash) external payable whenNotPaused onlyOwnerOf(_cardId) { require(msg.value==avatarFee, "fee must be equals to avatar price"); Card storage card = cards[_cardId]; uint256 tempHash = card.cardHash%1000000000000; //retain hash fixed section card.cardHash = tempHash.add(avatarHash.mul(1000000000000)); emit HashUpdated(_cardId, card.cardHash); } /// @dev Compute developer&#39;s fee /// @param _challengeFee - transaction fee function _calculateFee(uint256 _challengeFee) internal view returns (uint256) { return developerCut.mul(_challengeFee/10000); } /***********************************************************************************/ /* ADMIN FUNCTIONS /***********************************************************************************/ /** * @dev External function for drafting new card for Owner, for promotional purposes * @param _cardLevel initial level of card created, must be less or equals to 20 * @return uint of cardId */ function generateInitialCard(uint16 _cardLevel) external whenNotPaused onlyOwner returns (uint256) { require(address(marketplace) != address(0), "marketplace not set"); //need to set up marketplace before drafting new cards is allowed require(_cardLevel<=20, "maximum level cannot exceed 20"); //set maximum level at 20 that Owner can generate hogsmashToken.setApprovalForAllByContract(msg.sender, marketplace, true); //let marketplace have approval for escrow if the card goes on sale return _createCard(msg.sender, _cardLevel); //level 1 cards } /// @dev Function for contract owner to put tokens into ranks for events function distributeTokensToRank(uint[] ranks, uint256 tokensPerRank) external payable onlyOwner { require(msg.value == (tokensPerRank*ranks.length), "tokens must be enough to distribute among ranks"); uint i; for (i=0; i<ranks.length; i++) { rankTokens[ranks[i]] = rankTokens[ranks[i]].add(tokensPerRank); totalRankTokens = totalRankTokens.add(tokensPerRank); } } // @dev Allows contract owner to withdraw the all developer cut from the contract function withdrawBalance() external onlyOwner { address thisAddress = this; uint256 balance = thisAddress.balance; uint256 withdrawalSum = totalDeveloperCut; if (balance >= withdrawalSum) { totalDeveloperCut = 0; owner.transfer(withdrawalSum); } } } /***********************************************************************************/ /* INTERFACES /***********************************************************************************/ interface Marketplace { function isMarketplace() external returns (bool); } interface HogSmashToken { function ownerOf(uint256 _tokenId) external view returns (address); function balanceOf(address _owner) external view returns (uint256); function tokensOf(address _owner) external view returns (uint256[]); function mint(address _to) external returns (uint256 _tokenId); function setTokenURI(uint256 _tokenId, string _uri) external; function setApprovalForAllByContract(address _sender, address _to, bool _approved) external; }
function to allow contract owner to enable/disable starter pack sale
function setStarterPackOnSale(bool _newStarterPackOnSale) external onlyOwner { starterPackOnSale = _newStarterPackOnSale; }
8,074,549
./partial_match/1/0xb0849647424573358B9ECc9EA4DAb4Bb32399def/sources/contracts/implementations/HeyMintERC721AExtensionB.sol
Set the maximum mints allowed per a given transaction in the presale _mintsAllowed The new maximum mints allowed per transaction in the presale/
function setPresaleMintsAllowedPerTransaction( uint8 _mintsAllowed ) external onlyOwner { HeyMintStorage .state() .cfg .presaleMintsAllowedPerTransaction = _mintsAllowed; }
2,690,517
./partial_match/1/0xB5E2C8fa04Ae426167490a0437c4F20556c9B07C/sources/GovernanceCommunityGuarded.sol
Disable Community Guard/
function disableCommunityGuard() external override onlyCommunityKey onlyCommunityGuardEnabled { _communityGuardDisabled = true; emit CommunityGuardDisabled(true); }
2,813,165
pragma solidity ^0.5.16; import "./KToken.sol"; import "./KMCD.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./KineControllerInterface.sol"; import "./ControllerStorage.sol"; import "./Unitroller.sol"; import "./KineOracleInterface.sol"; import "./KineSafeMath.sol"; import "./Math.sol"; /** Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/Comptroller.sol * Modified to work in the Kine system. * Main modifications: * 1. removed Comp token related logics. * 2. removed interest rate model related logics. * 3. simplified calculations in mint, redeem, liquidity check, seize due to we don't use interest model/exchange rate. * 4. user can only supply kTokens (see KToken) and borrow Kine MCDs (see KMCD). Kine MCD's underlying can be considered as itself. * 5. removed error code propagation mechanism, using revert to fail fast and loudly. */ /** * @title Kine's Controller Contract * @author Kine */ contract Controller is ControllerStorage, KineControllerInterface, Exponential, ControllerErrorReporter { /// @notice Emitted when an admin supports a market event MarketListed(KToken kToken); /// @notice Emitted when an account enters a market event MarketEntered(KToken kToken, address account); /// @notice Emitted when an account exits a market event MarketExited(KToken kToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(KToken kToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when redemption params is changed by admin event NewRedemptionInitialPunishment(uint oldRedemptionInitialPunishmentMantissa, uint newRedemptionInitialPunishmentMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(KineOracleInterface oldPriceOracle, KineOracleInterface newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(KToken kToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a kToken is changed event NewBorrowCap(KToken indexed kToken, uint newBorrowCap); /// @notice Emitted when supply cap for a kToken is changed event NewSupplyCap(KToken indexed kToken, uint newSupplyCap); /// @notice Emitted when borrow/supply cap guardian is changed event NewCapGuardian(address oldCapGuardian, address newCapGuardian); // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can call this function"); _; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (KToken[] memory) { KToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param kToken The kToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, KToken kToken) external view returns (bool) { return markets[address(kToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param kTokens The list of addresses of the kToken markets to be enabled * @dev will revert if any market entering failed */ function enterMarkets(address[] memory kTokens) public { uint len = kTokens.length; for (uint i = 0; i < len; i++) { KToken kToken = KToken(kTokens[i]); addToMarketInternal(kToken, msg.sender); } } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param kToken The market to enter * @param borrower The address of the account to modify */ function addToMarketInternal(KToken kToken, address borrower) internal { Market storage marketToJoin = markets[address(kToken)]; require(marketToJoin.isListed, MARKET_NOT_LISTED); if (marketToJoin.accountMembership[borrower] == true) { // already joined return; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(kToken); emit MarketEntered(kToken, borrower); } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param kTokenAddress The address of the asset to be removed */ function exitMarket(address kTokenAddress) external { KToken kToken = KToken(kTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the kToken */ (uint tokensHeld, uint amountOwed) = kToken.getAccountSnapshot(msg.sender); /* Fail if the sender has a borrow balance */ require(amountOwed == 0, EXIT_MARKET_BALANCE_OWED); /* Fail if the sender is not permitted to redeem all of their tokens */ (bool allowed,) = redeemAllowedInternal(kTokenAddress, msg.sender, tokensHeld); require(allowed, EXIT_MARKET_REJECTION); Market storage marketToExit = markets[address(kToken)]; /* Succeed true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return; } /* Set kToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete kToken from the account’s list of assets */ // load into memory for faster iteration KToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == kToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken require(assetIndex < len, "accountAssets array broken"); // copy last item in list to location of item to be removed, reduce length by 1 KToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(kToken, msg.sender); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param kToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return false and reason if mint not allowed, otherwise return true and empty string */ function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool allowed, string memory reason) { if (mintGuardianPaused[kToken]) { allowed = false; reason = MINT_PAUSED; return (allowed, reason); } uint supplyCap = supplyCaps[kToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint totalSupply = KToken(kToken).totalSupply(); uint nextTotalSupply = totalSupply.add(mintAmount); if (nextTotalSupply > supplyCap) { allowed = false; reason = MARKET_SUPPLY_CAP_REACHED; return (allowed, reason); } } // Shh - currently unused minter; if (!markets[kToken].isListed) { allowed = false; reason = MARKET_NOT_LISTED; return (allowed, reason); } allowed = true; return (allowed, reason); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param kToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address kToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused kToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param kToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of kTokens to exchange for the underlying asset in the market * @return false and reason if redeem not allowed, otherwise return true and empty string */ function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool allowed, string memory reason) { return redeemAllowedInternal(kToken, redeemer, redeemTokens); } /** * @param kToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of kTokens to exchange for the underlying asset in the market * @return false and reason if redeem not allowed, otherwise return true and empty string */ function redeemAllowedInternal(address kToken, address redeemer, uint redeemTokens) internal view returns (bool allowed, string memory reason) { if (!markets[kToken].isListed) { allowed = false; reason = MARKET_NOT_LISTED; return (allowed, reason); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[kToken].accountMembership[redeemer]) { allowed = true; return (allowed, reason); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(redeemer, KToken(kToken), redeemTokens, 0); if (shortfall > 0) { allowed = false; reason = INSUFFICIENT_LIQUIDITY; return (allowed, reason); } allowed = true; return (allowed, reason); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param kToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address kToken, address redeemer, uint redeemTokens) external { // Shh - currently unused kToken; redeemer; require(redeemTokens != 0, REDEEM_TOKENS_ZERO); } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param kToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return false and reason if borrow not allowed, otherwise return true and empty string */ function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool allowed, string memory reason) { if (borrowGuardianPaused[kToken]) { allowed = false; reason = BORROW_PAUSED; return (allowed, reason); } if (!markets[kToken].isListed) { allowed = false; reason = MARKET_NOT_LISTED; return (allowed, reason); } if (!markets[kToken].accountMembership[borrower]) { // only kTokens may call borrowAllowed if borrower not in market require(msg.sender == kToken, "sender must be kToken"); // attempt to add borrower to the market addToMarketInternal(KToken(msg.sender), borrower); // it should be impossible to break the important invariant assert(markets[kToken].accountMembership[borrower]); } require(oracle.getUnderlyingPrice(kToken) != 0, "price error"); uint borrowCap = borrowCaps[kToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = KMCD(kToken).totalBorrows(); uint nextTotalBorrows = totalBorrows.add(borrowAmount); if (nextTotalBorrows > borrowCap) { allowed = false; reason = MARKET_BORROW_CAP_REACHED; return (allowed, reason); } } (, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(borrower, KToken(kToken), 0, borrowAmount); if (shortfall > 0) { allowed = false; reason = INSUFFICIENT_LIQUIDITY; return (allowed, reason); } allowed = true; return (allowed, reason); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param kToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address kToken, address borrower, uint borrowAmount) external { // Shh - currently unused kToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param kToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return false and reason if repay borrow not allowed, otherwise return true and empty string */ function repayBorrowAllowed( address kToken, address payer, address borrower, uint repayAmount) external returns (bool allowed, string memory reason) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[kToken].isListed) { allowed = false; reason = MARKET_NOT_LISTED; } allowed = true; return (allowed, reason); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param kToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address kToken, address payer, address borrower, uint actualRepayAmount) external { // Shh - currently unused kToken; payer; borrower; actualRepayAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param kTokenBorrowed Asset which was borrowed by the borrower * @param kTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid * @return false and reason if liquidate borrow not allowed, otherwise return true and empty string */ function liquidateBorrowAllowed( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (bool allowed, string memory reason) { // Shh - currently unused liquidator; if (!markets[kTokenBorrowed].isListed || !markets[kTokenCollateral].isListed) { allowed = false; reason = MARKET_NOT_LISTED; return (allowed, reason); } if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) { allowed = false; reason = CONTROLLER_MISMATCH; return (allowed, reason); } /* The liquidator may not repay more than what is allowed by the closeFactor */ /* Only KMCD has borrow related logics */ uint borrowBalance = KMCD(kTokenBorrowed).borrowBalance(borrower); uint maxClose = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { allowed = false; reason = TOO_MUCH_REPAY; return (allowed, reason); } allowed = true; return (allowed, reason); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param kTokenBorrowed Asset which was borrowed by the borrower * @param kTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address kTokenBorrowed, address kTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused kTokenBorrowed; kTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param kTokenCollateral Asset which was used as collateral and will be seized * @param kTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize * @return false and reason if seize not allowed, otherwise return true and empty string */ function seizeAllowed( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (bool allowed, string memory reason) { if (seizeGuardianPaused) { allowed = false; reason = SEIZE_PAUSED; return (allowed, reason); } // Shh - currently unused seizeTokens; liquidator; borrower; if (!markets[kTokenCollateral].isListed || !markets[kTokenBorrowed].isListed) { allowed = false; reason = MARKET_NOT_LISTED; return (allowed, reason); } if (KToken(kTokenCollateral).controller() != KToken(kTokenBorrowed).controller()) { allowed = false; reason = CONTROLLER_MISMATCH; return (allowed, reason); } allowed = true; return (allowed, reason); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param kTokenCollateral Asset which was used as collateral and will be seized * @param kTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address kTokenCollateral, address kTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused kTokenCollateral; kTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param kToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of kTokens to transfer * @return false and reason if seize not allowed, otherwise return true and empty string */ function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool allowed, string memory reason) { if (transferGuardianPaused) { allowed = false; reason = TRANSFER_PAUSED; return (allowed, reason); } // not used currently dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens return redeemAllowedInternal(kToken, src, transferTokens); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param kToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of kTokens to transfer */ function transferVerify(address kToken, address src, address dst, uint transferTokens) external { // Shh - currently unused kToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `kTokenBalance` is the number of kTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. * In Kine system, user can only borrow Kine MCD, the `borrowBalance` is the amount of Kine MCD account has borrowed. */ struct AccountLiquidityLocalVars { uint sumStaking; uint sumCollateral; uint sumBorrowPlusEffects; uint kTokenBalance; uint borrowBalance; uint oraclePriceMantissa; Exp collateralFactor; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (account liquidity in excess of collateral requirements, * account shortfall below collateral requirements, * account staking asset value, * account collateral value) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (account liquidity in excess of collateral requirements, * account shortfall below collateral requirements * account staking asset value, * account collateral value) */ function getAccountLiquidityInternal(address account) internal view returns (uint, uint, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, KToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param kTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address kTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint) { (uint liquidity, uint shortfall,,) = getHypotheticalAccountLiquidityInternal(account, KToken(kTokenModify), redeemTokens, borrowAmount); return (liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param kTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, KToken kTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (uint, uint, uint, uint) { AccountLiquidityLocalVars memory vars; // For each asset the account is in KToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { KToken asset = assets[i]; // Read the balances from the kToken (vars.kTokenBalance, vars.borrowBalance) = asset.getAccountSnapshot(account); vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(address(asset)); require(vars.oraclePriceMantissa != 0, "price error"); vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa}); // Pre-compute a conversion factor vars.tokensToDenom = mulExp(vars.collateralFactor, vars.oraclePrice); // sumStaking += oraclePrice * kTokenBalance vars.sumStaking = mulScalarTruncateAddUInt(vars.oraclePrice, vars.kTokenBalance, vars.sumStaking); // sumCollateral += tokensToDenom * kTokenBalance vars.sumCollateral = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.kTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with kTokenModify if (asset == kTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0, vars.sumStaking, vars.sumCollateral); } else { return (0, vars.sumBorrowPlusEffects - vars.sumCollateral, vars.sumStaking, vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in kMCD.liquidateBorrowFresh) * @param kTokenBorrowed The address of the borrowed kToken * @param kTokenCollateral The address of the collateral kToken * @param actualRepayAmount The amount of kTokenBorrowed underlying to convert into kTokenCollateral tokens * @return number of kTokenCollateral tokens to be seized in a liquidation */ function liquidateCalculateSeizeTokens(address target, address kTokenBorrowed, address kTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(kTokenBorrowed); uint priceCollateralMantissa = oracle.getUnderlyingPrice(kTokenCollateral); require(priceBorrowedMantissa != 0 && priceCollateralMantissa != 0, "price error"); uint cf = markets[address(kTokenCollateral)].collateralFactorMantissa; (uint liquidity, uint shortfall, uint stakingValue, uint collateralValue) = getAccountLiquidityInternal(target); uint incentiveOrPunishment; if (shortfall > 0) { // a liquidation occurs, incentive will be adjusted as below // adjusted liquidation incentive = min((1-cf)/2 + 100%, (shortfall/collateralValue/cf)^2 + liquidationIncentive) uint r = shortfall.mul(expScale).div(collateralValue).mul(expScale).div(cf); incentiveOrPunishment = Math.min(mantissaOne.sub(cf).div(2).add(mantissaOne), r.mul(r).div(expScale).add(liquidationIncentiveMantissa)); } else { require(!redemptionPaused, "Redemption paused"); require(!redemptionPausedPerAsset[kTokenCollateral], "Asset Redemption paused"); // a redemption occurs, punishment will be adjusted as below // adjusted redemption punishment = 1 - (redemptionInitialPunishment + (liquidity/collateralValue*cf)^2) uint r = liquidity.mul(expScale).div(collateralValue).mul(cf).div(expScale); incentiveOrPunishment = mantissaOne.sub(redemptionInitialPunishmentMantissa.add(r.mul(r).div(expScale))); } /* * calculate the number of collateral tokens to seize: * seizeTokens = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral */ Exp memory ratio = divExp(mulExp(incentiveOrPunishment, priceBorrowedMantissa), Exp({mantissa : priceCollateralMantissa})); return mulScalarTruncate(ratio, actualRepayAmount); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the controller * @dev Admin function to set a new price oracle */ function _setPriceOracle(KineOracleInterface newOracle) external onlyAdmin() { KineOracleInterface oldOracle = oracle; oracle = newOracle; emit NewPriceOracle(oldOracle, newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint newCloseFactorMantissa) external onlyAdmin() { require(newCloseFactorMantissa <= closeFactorMaxMantissa, INVALID_CLOSE_FACTOR); require(newCloseFactorMantissa >= closeFactorMinMantissa, INVALID_CLOSE_FACTOR); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param kToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor(KToken kToken, uint newCollateralFactorMantissa) external onlyAdmin() { // Verify market is listed Market storage market = markets[address(kToken)]; require(market.isListed, MARKET_NOT_LISTED); Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa}); require(!lessThanExp(highLimit, newCollateralFactorExp), INVALID_COLLATERAL_FACTOR); // If collateral factor != 0, fail if price == 0 require(newCollateralFactorMantissa == 0 || oracle.getUnderlyingPrice(address(kToken)) != 0, "price error"); // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(kToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyAdmin() { require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, INVALID_LIQUIDATION_INCENTIVE); require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, INVALID_LIQUIDATION_INCENTIVE); uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param kToken The address of the market (token) to list */ function _supportMarket(KToken kToken) external onlyAdmin() { require(!markets[address(kToken)].isListed, MARKET_ALREADY_LISTED); kToken.isKToken(); // Sanity check to make sure its really a KToken markets[address(kToken)] = Market({isListed : true, collateralFactorMantissa : 0}); _addMarketInternal(address(kToken)); emit MarketListed(kToken); } function _addMarketInternal(address kToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != KToken(kToken), MARKET_ALREADY_ADDED); } allMarkets.push(KToken(kToken)); } /** * @notice Set the given borrow caps for the given kToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or capGuardian can call this function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param kTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(KToken[] calldata kTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set borrow caps"); uint numMarkets = kTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint i = 0; i < numMarkets; i++) { borrowCaps[address(kTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(kTokens[i], newBorrowCaps[i]); } } /** * @notice Set the given supply caps for the given kToken markets. Supplying that brings total supply to or above supply cap will revert. * @dev Admin or capGuardian can call this function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. * @param kTokens The addresses of the markets (tokens) to change the supply caps for * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. */ function _setMarketSupplyCaps(KToken[] calldata kTokens, uint[] calldata newSupplyCaps) external { require(msg.sender == admin || msg.sender == capGuardian, "only admin or cap guardian can set supply caps"); uint numMarkets = kTokens.length; uint numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint i = 0; i < numMarkets; i++) { supplyCaps[address(kTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(kTokens[i], newSupplyCaps[i]); } } /** * @notice Admin function to change the Borrow and Supply Cap Guardian * @param newCapGuardian The address of the new Cap Guardian */ function _setCapGuardian(address newCapGuardian) external onlyAdmin() { address oldCapGuardian = capGuardian; capGuardian = newCapGuardian; emit NewCapGuardian(oldCapGuardian, newCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian */ function _setPauseGuardian(address newPauseGuardian) external onlyAdmin() { address oldPauseGuardian = pauseGuardian; pauseGuardian = newPauseGuardian; emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); } function _setMintPaused(KToken kToken, bool state) public returns (bool) { require(markets[address(kToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause"); mintGuardianPaused[address(kToken)] = state; emit ActionPaused(kToken, "Mint", state); return state; } function _setBorrowPaused(KToken kToken, bool state) public returns (bool) { require(markets[address(kToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause"); borrowGuardianPaused[address(kToken)] = state; emit ActionPaused(kToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _setRedemptionPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause"); redemptionPaused = state; emit ActionPaused("Redemption", state); return state; } function _setRedemptionPausedPerAsset(KToken kToken, bool state) public returns (bool) { require(markets[address(kToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause/unpause"); redemptionPausedPerAsset[address(kToken)] = state; emit ActionPaused(kToken, "Redemption", state); return state; } function _setRedemptionInitialPunishment(uint newRedemptionInitialPunishmentMantissa) external onlyAdmin() { uint oldRedemptionInitialPunishmentMantissa = redemptionInitialPunishmentMantissa; redemptionInitialPunishmentMantissa = newRedemptionInitialPunishmentMantissa; emit NewRedemptionInitialPunishment(oldRedemptionInitialPunishmentMantissa, newRedemptionInitialPunishmentMantissa); } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); unitroller._acceptImplementation(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (KToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } function getOracle() external view returns (address) { return address(oracle); } }
Add the market to the markets mapping and set it as listed Admin function to set isListed and add support for the market kToken The address of the market (token) to list/ Sanity check to make sure its really a KToken
function _supportMarket(KToken kToken) external onlyAdmin() { require(!markets[address(kToken)].isListed, MARKET_ALREADY_LISTED); kToken.isKToken(); _addMarketInternal(address(kToken)); emit MarketListed(kToken); }
6,376,638
pragma solidity ^0.5.4; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Eternal Storage for the Reserve Token * * @dev Eternal Storage facilitates future upgrades. * * If Reserve chooses to release an upgraded contract for the Reserve in the future, Reserve * will have the option of reusing the deployed version of this data contract to simplify migration. * * The use of this contract does not imply that Reserve will choose to do a future upgrade, nor that * any future upgrades will necessarily re-use this storage. It merely provides option value. */ contract ReserveEternalStorage { using SafeMath for uint256; // ===== auth ===== address public owner; address public escapeHatch; event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); event EscapeHatchTransferred(address indexed oldEscapeHatch, address indexed newEscapeHatch); /// On construction, set auth fields. constructor(address escapeHatchAddress) public { owner = msg.sender; escapeHatch = escapeHatchAddress; } /// Only run modified function if sent by `owner`. modifier onlyOwner() { require(msg.sender == owner, "onlyOwner"); _; } /// Set `owner`. function transferOwnership(address newOwner) external { require(msg.sender == owner || msg.sender == escapeHatch, "not authorized"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /// Set `escape hatch`. function transferEscapeHatch(address newEscapeHatch) external { require(msg.sender == escapeHatch, "not authorized"); emit EscapeHatchTransferred(escapeHatch, newEscapeHatch); escapeHatch = newEscapeHatch; } // ===== balance ===== mapping(address => uint256) public balance; /// Add `value` to `balance[key]`, unless this causes integer overflow. /// /// @dev This is a slight divergence from the strict Eternal Storage pattern, but it reduces the gas /// for the by-far most common token usage, it's a *very simple* divergence, and `setBalance` is /// available anyway. function addBalance(address key, uint256 value) external onlyOwner { balance[key] = balance[key].add(value); } /// Subtract `value` from `balance[key]`, unless this causes integer underflow. function subBalance(address key, uint256 value) external onlyOwner { balance[key] = balance[key].sub(value); } /// Set `balance[key]` to `value`. function setBalance(address key, uint256 value) external onlyOwner { balance[key] = value; } // ===== allowed ===== mapping(address => mapping(address => uint256)) public allowed; /// Set `to`'s allowance of `from`'s tokens to `value`. function setAllowed(address from, address to, uint256 value) external onlyOwner { allowed[from][to] = value; } // ===== frozenTime ===== /// @dev When `frozenTime[addr] == 0`, `addr` is not frozen. This is the normal state. /// When `frozenTime[addr] == t` and `t > 0`, `addr` was last frozen at timestamp `t`. /// So, to unfreeze an address `addr`, set `frozenTime[addr] = 0`. mapping(address => uint256) public frozenTime; /// Set `frozenTime[who]` to `time`. function setFrozenTime(address who, uint256 time) external onlyOwner { frozenTime[who] = time; } } /** * @title The standard ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address, uint256) external returns (bool); function approve(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); function allowance(address, address) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed holder, address indexed spender, uint256 value); } /** * @title The Reserve Token * @dev An ERC-20 token with minting, burning, pausing, and user freezing. * Based on OpenZeppelin's [implementation](https://github.com/OpenZeppelin/openzeppelin-solidity/blob/41aa39afbc13f0585634061701c883fe512a5469/contracts/token/ERC20/ERC20.sol). * * Non-constant-sized data is held in ReserveEternalStorage, * to facilitate potential future upgrades. */ contract Reserve is IERC20 { using SafeMath for uint256; // Non-constant-sized data ReserveEternalStorage internal data; // Basic token data string public name = "Reserve"; string public symbol = "RSV"; uint8 public constant decimals = 18; uint256 public totalSupply; // Paused data bool public paused; // Auth roles address public owner; address public minter; address public pauser; address public freezer; address public nominatedOwner; // Auth role change events event OwnerChanged(address indexed newOwner); event MinterChanged(address indexed newMinter); event PauserChanged(address indexed newPauser); event FreezerChanged(address indexed newFreezer); // Pause events event Paused(address indexed account); event Unpaused(address indexed account); // Name change event event NameChanged(string newName, string newSymbol); // Law enforcement events event Frozen(address indexed freezer, address indexed account); event Unfrozen(address indexed freezer, address indexed account); event Wiped(address indexed freezer, address indexed wiped); /// Initialize critical fields. constructor() public { data = new ReserveEternalStorage(msg.sender); owner = msg.sender; pauser = msg.sender; // Other roles deliberately default to the zero address. } /// Accessor for eternal storage contract address. function getEternalStorageAddress() external view returns(address) { return address(data); } // ==== Admin functions ==== /// Modifies a function to only run if sent by `role`. modifier only(address role) { require(msg.sender == role, "unauthorized: not role holder"); _; } /// Modifies a function to only run if sent by `role` or the contract's `owner`. modifier onlyOwnerOr(address role) { require(msg.sender == owner || msg.sender == role, "unauthorized: not role holder and not owner"); _; } /// Change who holds the `minter` role. function changeMinter(address newMinter) external onlyOwnerOr(minter) { minter = newMinter; emit MinterChanged(newMinter); } /// Change who holds the `pauser` role. function changePauser(address newPauser) external onlyOwnerOr(pauser) { pauser = newPauser; emit PauserChanged(newPauser); } /// Change who holds the `freezer` role. function changeFreezer(address newFreezer) external onlyOwnerOr(freezer) { freezer = newFreezer; emit FreezerChanged(newFreezer); } /// Nominate a new `owner`. We want to ensure that `owner` is always valid, so we don't /// actually change `owner` to `nominatedOwner` until `nominatedOwner` calls `acceptOwnership`. function nominateNewOwner(address nominee) external only(owner) { nominatedOwner = nominee; } /// Accept nomination for ownership. /// This completes the `nominateNewOwner` handshake. function acceptOwnership() external onlyOwnerOr(nominatedOwner) { if (msg.sender != owner) { emit OwnerChanged(msg.sender); } owner = msg.sender; nominatedOwner = address(0); } /// Set `owner` to 0. /// Only do this to deliberately lock in the current permissions. function renounceOwnership() external only(owner) { owner = address(0); emit OwnerChanged(owner); } /// Make a different address own the EternalStorage contract. /// This will break this contract, so only do it if you're /// abandoning this contract, e.g., for an upgrade. function transferEternalStorage(address newOwner) external only(owner) { data.transferOwnership(newOwner); } /// Change the name and ticker symbol of this token. function changeName(string calldata newName, string calldata newSymbol) external only(owner) { name = newName; symbol = newSymbol; emit NameChanged(newName, newSymbol); } /// Pause the contract. function pause() external only(pauser) { paused = true; emit Paused(pauser); } /// Unpause the contract. function unpause() external only(pauser) { paused = false; emit Unpaused(pauser); } /// Modifies a function to run only when the contract is not paused. modifier notPaused() { require(!paused, "contract is paused"); _; } /// Freeze token transactions for a particular address. function freeze(address account) external only(freezer) { require(data.frozenTime(account) == 0, "account already frozen"); // In `wipe` we use block.timestamp (aka `now`) to check that enough time has passed since // this freeze happened. That required time delay -- 4 weeks -- is a long time relative to // the maximum drift of block.timestamp, so it is fine to trust the miner here. // solium-disable-next-line security/no-block-members data.setFrozenTime(account, now); emit Frozen(freezer, account); } /// Unfreeze token transactions for a particular address. function unfreeze(address account) external only(freezer) { require(data.frozenTime(account) > 0, "account not frozen"); data.setFrozenTime(account, 0); emit Unfrozen(freezer, account); } /// Modifies a function to run only when the `account` is not frozen. modifier notFrozen(address account) { require(data.frozenTime(account) == 0, "account frozen"); _; } /// Burn the balance of an account that has been frozen for at least 4 weeks. function wipe(address account) external only(freezer) { require(data.frozenTime(account) > 0, "cannot wipe unfrozen account"); // See commentary above about using block.timestamp. // solium-disable-next-line security/no-block-members require(data.frozenTime(account) + 4 weeks < now, "cannot wipe frozen account before 4 weeks"); _burn(account, data.balance(account)); emit Wiped(freezer, account); } // ==== Token transfers, allowances, minting, and burning ==== /// @return how many attotokens are held by `holder`. function balanceOf(address holder) external view returns (uint256) { return data.balance(holder); } /// @return how many attotokens `holder` has allowed `spender` to control. function allowance(address holder, address spender) external view returns (uint256) { return data.allowed(holder, spender); } /// Transfer `value` attotokens from `msg.sender` to `to`. function transfer(address to, uint256 value) external notPaused notFrozen(msg.sender) notFrozen(to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * Approve `spender` to spend `value` attotokens on behalf of `msg.sender`. * * Beware that changing a nonzero allowance with this method brings the risk that * someone may use both the old and the new allowance by unfortunate transaction ordering. One * way to mitigate this risk is to first reduce the spender's allowance * to 0, and then set the desired value afterwards, per * [this ERC-20 issue](https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729). * * A simpler workaround is to use `increaseAllowance` or `decreaseAllowance`, below. * * @param spender address The address which will spend the funds. * @param value uint256 How many attotokens to allow `spender` to spend. */ function approve(address spender, uint256 value) external notPaused notFrozen(msg.sender) notFrozen(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /// Transfer approved tokens from one address to another. /// @param from address The address to send tokens from. /// @param to address The address to send tokens to. /// @param value uint256 The number of attotokens to send. function transferFrom(address from, address to, uint256 value) external notPaused notFrozen(msg.sender) notFrozen(from) notFrozen(to) returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, data.allowed(from, msg.sender).sub(value)); return true; } /// Increase `spender`'s allowance of the sender's tokens. /// @dev From MonolithDAO Token.sol /// @param spender The address which will spend the funds. /// @param addedValue How many attotokens to increase the allowance by. function increaseAllowance(address spender, uint256 addedValue) external notPaused notFrozen(msg.sender) notFrozen(spender) returns (bool) { _approve(msg.sender, spender, data.allowed(msg.sender, spender).add(addedValue)); return true; } /// Decrease `spender`'s allowance of the sender's tokens. /// @dev From MonolithDAO Token.sol /// @param spender The address which will spend the funds. /// @param subtractedValue How many attotokens to decrease the allowance by. function decreaseAllowance(address spender, uint256 subtractedValue) external notPaused notFrozen(msg.sender) // This is the one case in which changing the allowance of a frozen spender is allowed. // notFrozen(spender) returns (bool) { _approve(msg.sender, spender, data.allowed(msg.sender, spender).sub(subtractedValue)); return true; } /// Mint `value` new attotokens to `account`. function mint(address account, uint256 value) external notPaused notFrozen(account) only(minter) { require(account != address(0), "can't mint to address zero"); totalSupply = totalSupply.add(value); data.addBalance(account, value); emit Transfer(address(0), account, value); } /// Burn `value` attotokens from `account`, if sender has that much allowance from `account`. function burnFrom(address account, uint256 value) external notPaused notFrozen(account) only(minter) { _burn(account, value); _approve(account, msg.sender, data.allowed(account, msg.sender).sub(value)); } /// @dev Transfer of `value` attotokens from `from` to `to`. /// Internal; doesn't check permissions. function _transfer(address from, address to, uint256 value) internal { require(to != address(0), "can't transfer to address zero"); data.subBalance(from, value); data.addBalance(to, value); emit Transfer(from, to, value); } /// @dev Burn `value` attotokens from `account`. /// Internal; doesn't check permissions. function _burn(address account, uint256 value) internal { require(account != address(0), "can't burn from address zero"); totalSupply = totalSupply.sub(value); data.subBalance(account, value); emit Transfer(account, address(0), value); } /// @dev Set `spender`'s allowance on `holder`'s tokens to `value` attotokens. /// Internal; doesn't check permissions. function _approve(address holder, address spender, uint256 value) internal { require(spender != address(0), "spender cannot be address zero"); require(holder != address(0), "holder cannot be address zero"); data.setAllowed(holder, spender, value); emit Approval(holder, spender, value); } }
Freeze token transactions for a particular address. In `wipe` we use block.timestamp (aka `now`) to check that enough time has passed since this freeze happened. That required time delay -- 4 weeks -- is a long time relative to the maximum drift of block.timestamp, so it is fine to trust the miner here. solium-disable-next-line security/no-block-members
function freeze(address account) external only(freezer) { require(data.frozenTime(account) == 0, "account already frozen"); data.setFrozenTime(account, now); emit Frozen(freezer, account); }
1,777,817
./full_match/4/0x99ed61977D6b777b4b31FbF0838A3E97465bcADb/sources/contracts/dob.sol
Throws unless `msg.sender` is the current owner, an authorized operator, or the approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. The caller is responsible to confirm that `_to` is capable of receiving NFTs or else they maybe be permanently lost. _from The current owner of the NFT. _to The new owner. _tokenId The NFT to transfer./
function transferFrom( address _from, address _to, uint256 _tokenId) external override canTransfer(_tokenId) validNFToken(_tokenId) payable { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, "Only owner can transfer"); require(_to != address(0), "Invalid destination address"); _transfer(_to, _tokenId); }
12,345,058
pragma solidity ^0.5.10; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @dev Implements a very simple issuance process for tokens contract Issuance is Ownable, ERC20 { event Invested(address investor, uint256 investment); event Cancelled(address investor); event Claimed(address investor, uint256 tokens); event GoneLive(uint256 proceedings); ERC20 public currency; bool public live; uint256 public price; mapping(address => uint256) public investments; constructor(uint256 issuePrice, address currencyAddress) public Ownable() ERC20() { price = issuePrice; currency = ERC20(currencyAddress); } /// @dev Invest into the issuance by sending ether to this function function invest(uint256 investment) public { require(live == false, "Cannot invest if live."); require( investment % price == 0, "Cannot invest a fraction of the price." ); currency.transferFrom(msg.sender, address(this), investment); investments[msg.sender] = investments[msg.sender] + investment; emit Invested(msg.sender, investments[msg.sender]); } /// @dev Function for an investor to cancel his investment function cancel() public { require(live == false, "Cannot cancel if live."); uint256 tokens = investments[msg.sender]; delete investments[msg.sender]; currency.transfer(msg.sender, tokens); emit Cancelled(msg.sender); } /// @dev Function to go live and withdraw proceedings function goLive() public onlyOwner { live = true; uint256 proceedings = currency.balanceOf(address(this)); currency.transfer(owner(), proceedings); emit GoneLive(proceedings); } /// @dev Use this function to claim your issuance tokens function claim() public { require(live == true, "Cannot claim until live."); uint256 tokens = investments[msg.sender] / price; delete investments[msg.sender]; _mint(msg.sender, tokens); emit Claimed(msg.sender, tokens); } }
Function for an investor to cancel his investment
function cancel() public { require(live == false, "Cannot cancel if live."); uint256 tokens = investments[msg.sender]; delete investments[msg.sender]; currency.transfer(msg.sender, tokens); emit Cancelled(msg.sender); }
991,316
pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0b0a1b0a2f0e17060002150a01410c00">[email&#160;protected]</a>> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract MemeToken is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new meme comes into existence. event Birth(uint256 tokenId, uint256 metadata, string text, address owner); /// @dev The TokenSold event is fired whenever a meme is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address newOwner, uint256 metadata, string text); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoMemes"; // solhint-disable-line string public constant SYMBOL = "CM"; // solhint-disable-line uint256 private startingPrice = 0.001 ether; uint256 private constant PROMO_CREATION_LIMIT = 50000; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.5 ether; /*** STORAGE ***/ /// @dev A mapping from meme IDs to the address that owns them. All memes have /// some valid owner address. mapping (uint256 => address) public memeIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from memeIDs to an address that has been approved to call /// transferFrom(). Each meme can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public memeIndexToApproved; // @dev A mapping from memeIDs to the price of the token. mapping (uint256 => uint256) private memeIndexToPrice; // The address of the account that can execute special actions. // Not related to Dogecoin, just a normal Doge. address public dogeAddress; // Robot9000 address for automation. // Not related to r9k, just a normal robot. address public r9kAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Meme { uint256 metadata; string text; } // All your memes are belong to us. Meme[] private memes; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for Doge functionality modifier onlyDoge() { require(msg.sender == dogeAddress); _; } /// @dev Access modifier for Robot functionality modifier onlyr9k() { require(msg.sender == r9kAddress); _; } /// @dev Access modifier for Doge and Robot functionality modifier onlyDogeAndr9k() { require( msg.sender == dogeAddress || msg.sender == r9kAddress ); _; } /*** CONSTRUCTOR ***/ function MemeToken() public { dogeAddress = msg.sender; r9kAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); memeIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo meme with the given metadata and text, with given _price and /// assignes it to an address. function createPromoMeme(address _owner, uint256 _metadata, string _text, uint256 _price) public onlyDogeAndr9k { require(promoCreatedCount < PROMO_CREATION_LIMIT); address memeOwner = _owner; if (memeOwner == address(0)) { memeOwner = dogeAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createMeme(_metadata, _text, memeOwner, _price); } /// @dev Creates a new user-generated meme with the given metadata and text, with given _price and /// assignes it to an address. function createUserMeme(address _owner, uint256 _metadata, string _text, uint256 _price) public onlyDogeAndr9k { address memeOwner = _owner; if (memeOwner == address(0)) { memeOwner = dogeAddress; } if (_price <= 0) { _price = startingPrice; } _createMeme(_metadata, _text, memeOwner, _price); } /// @dev Creates a new meme with the given name. function createContractMeme(uint256 _metadata, string _text) public onlyDogeAndr9k { _createMeme(_metadata, _text, address(this), startingPrice); } /// @notice Returns all the relevant information about a specific meme. /// @param _tokenId The tokenId of the meme of interest. function getMeme(uint256 _tokenId) public view returns ( uint256 metadata, string text, uint256 sellingPrice, address owner ) { Meme storage meme = memes[_tokenId]; metadata = meme.metadata; text = meme.text; sellingPrice = memeIndexToPrice[_tokenId]; owner = memeIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = memeIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyDoge { _payout(_to); } // Allows someone to send ether and obtain the meme function purchase(uint256 _tokenId) public payable { address oldOwner = memeIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = memeIndexToPrice[_tokenId]; // Making sure meme owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 97), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage memeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100); } else if (sellingPrice < secondStepLimit) { // second stage memeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); } else { // third stage memeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 125), 100); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1 - 0.05) } TokenSold(_tokenId, sellingPrice, memeIndexToPrice[_tokenId], oldOwner, newOwner, memes[_tokenId].metadata, memes[_tokenId].text); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return memeIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as Doge. Only available to the current Doge. /// @param _newDoge The address of the new Doge function setDoge(address _newDoge) public onlyDoge { require(_newDoge != address(0)); dogeAddress = _newDoge; } /// @dev Assigns a new address to act as Robot. Only available to the current Doge. /// @param _newRobot The address of the new Robot function setRobot(address _newRobot) public onlyDoge { require(_newRobot != address(0)); r9kAddress = _newRobot; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a meme /// @param _tokenId The ID of the meme that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = memeIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose meme tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire memes array looking for memes belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 memeCount = totalSupply(); uint256 resultIndex = 0; uint256 memeId; for (memeId = 0; memeId <= memeCount; memeId++) { if (memeIndexToOwner[memeId] == _owner) { result[resultIndex] = memeId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return memes.length; } /// Owner initates the transfer of the meme to another account /// @param _to The address for the meme to be transferred to. /// @param _tokenId The ID of the meme that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return memeIndexToApproved[_tokenId] == _to; } /// For creating a new meme function _createMeme(uint256 _metadata, string _text, address _owner, uint256 _price) private { Meme memory _meme = Meme({ metadata: _metadata, text: _text }); uint256 newMemeId = memes.push(_meme) - 1; // It&#39;s probably never going to happen, 2^64 memes are A LOT, but // let&#39;s just be 100% sure we never let this happen. require(newMemeId == uint256(uint64(newMemeId))); Birth(newMemeId, _metadata, _text, _owner); memeIndexToPrice[newMemeId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newMemeId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == memeIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { dogeAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific meme to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of memes is capped to 2^32 we can&#39;t overflow this ownershipTokenCount[_to]++; //transfer ownership memeIndexToOwner[_tokenId] = _to; // When creating new memes _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete memeIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Owner initates the transfer of the meme to another account _to The address for the meme to be transferred to. _tokenId The ID of the meme that can be transferred if this call succeeds. Required for ERC-721 compliance.
function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); }
6,648,118
pragma solidity ^0.4.15; /**************************************************************** * * Name of the project: Genevieve GXE ICO * Contract name: NewIco * Author: Juan Livingston @ Ethernity.live * ****************************************************************/ 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); } 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); function burn(address spender, uint256 value) returns (bool); // Optional event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC223 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function name() constant returns (string _name); function symbol() constant returns (string _symbol); function decimals() constant returns (uint8 _decimals); function totalSupply() constant returns (uint256 _supply); function transfer(address to, uint value) returns (bool ok); function transfer(address to, uint value, bytes data) returns (bool ok); function transfer(address to, uint value, bytes data, string custom_fallback) returns (bool ok); function transferFrom(address from, address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } contract Whitelist { mapping (address => bool) public registered; } contract GXESwapper{ address public authorizedCaller; address public collectorAddress; address public owner; address public whitelistAdd; address public tokenAdd; address public tokenSpender; uint public initialPrice; uint public initialTime; uint tokenPrice; uint increasePerBlock; uint increasePerBlockDiv; bool public autoPrice; bool public isPaused; uint public minAcceptedETH; uint public tokenDecimals; uint public tokenMult; uint8 public stage; // Main counters uint public totalReceived; uint public totalSent; // Constructor function with main constants and variables function GXESwapper() { authorizedCaller = msg.sender; owner = msg.sender; collectorAddress = 0x24350803BFcE6E9D1f4baE0940E43af186A6D12C; tokenAdd = 0x106b419718298f91ca576728A670597fb2e0eE4e; tokenSpender = 0x24350803BFcE6E9D1f4baE0940E43af186A6D12C; whitelistAdd = 0xad56C554f32D51526475d541F5DeAabE1534854d; authorized[authorizedCaller] = true; minAcceptedETH = 0.05 ether; tokenDecimals = 10; tokenMult = 10 ** tokenDecimals; initialPrice = 10000 * tokenMult; // 10,000 tokens per ether (0,0001 eth/token) tokenPrice = initialPrice; autoPrice = false; initialTime = now; increasePerBlock = 159; // Percentage to add per each block respect original price, in cents increasePerBlockDiv = 1000000000; // According to specs: 1.59% x 10 ^ -5 (= 159 / 10 ^ 7) == 0.055 % per day stage = 1; } // Mapping to store swaps made and authorized callers mapping(address => uint) public receivedFrom; mapping(address => uint) public sentTo; mapping(address => bool) public authorized; // Event definitions event TokensSent(address _address , uint _received , uint _sent); // Modifier for authorized calls modifier isAuthorized() { require(authorized[msg.sender]); _; } modifier isNotPaused() { require(!isPaused); _; } // Function borrowed from ds-math. function mul(uint x, uint y) internal returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // Falback function, invoked each time ethers are received function () payable { makeSwapInternal(); } // Ether swap, activated by the fallback function after receiving ethers function makeSwapInternal() private isNotPaused { // Main function, called internally when ethers are received require(stage>0 && stage<3 && msg.value >= minAcceptedETH); Whitelist wl = Whitelist(whitelistAdd); if (stage==1 || stage==2 ) require(wl.registered(msg.sender)); ERC223 GXVCtoken = ERC223(tokenAdd); address _address = msg.sender; uint _value = msg.value; uint _price = getPrice(); uint tokensToSend = _price * _value / 10 ** 18; receivedFrom[_address] += _value; totalReceived += _value; sentTo[_address] += tokensToSend; totalSent += tokensToSend; //Send tokens require(GXVCtoken.transferFrom(tokenSpender,_address,tokensToSend)); // Log tokens sent for ethers; TokensSent(_address,_value,tokensToSend); // Send ethers to collector require(collectorAddress.send(_value)); } function getPrice() constant public returns(uint _price){ if (autoPrice) { return calculatePrice(now); } else { return tokenPrice; } } function getCurrentStage() public constant returns(uint8 _stage){ return stage; } function calculatePrice(uint _when) constant public returns(uint _result){ if (_when == 0) _when = now; // 25 are estimated of 25 seconds per block uint delay = (_when - initialTime) / 25; uint factor = delay * increasePerBlock; uint multip = initialPrice * factor; uint result = initialPrice - multip / increasePerBlockDiv; require (result<=initialPrice); return result; } function changeToStage(uint8 _stage) isAuthorized returns(bool) { require(stage < _stage && _stage < 4); stage = _stage; return true; } function pause() public isAuthorized { isPaused = true; } function resume() public isAuthorized { isPaused = false; } function setManualPrice(uint _price) public isAuthorized { autoPrice = false; tokenPrice = _price; } function setAutoPrice() public isAuthorized { autoPrice = true; } function setInitialTime() public isAuthorized { initialTime = now; } function getNow() public constant returns(uint _now){ return now; } function flushEthers() public isAuthorized { // Send ether to collector require( collectorAddress.send(this.balance) ); } function changeMinAccEthers(uint _newMin) public isAuthorized { minAcceptedETH = _newMin; } function addAuthorized(address _address) public isAuthorized { authorized[_address] = true; } function removeAuthorized(address _address) public isAuthorized { require(_address != owner); authorized[_address] = false; } function changeOwner(address _address) public { require(msg.sender == owner); owner = _address; } // To manage ERC20 tokens in case of accidental sending to the contract function sendTokens(address _address , uint256 _amount) isAuthorized returns (bool success) { ERC20Basic token = ERC20Basic( tokenAdd ); require( token.transfer(_address , _amount ) ); return true; } }
25 are estimated of 25 seconds per block
function calculatePrice(uint _when) constant public returns(uint _result){ if (_when == 0) _when = now; uint delay = (_when - initialTime) / 25; uint factor = delay * increasePerBlock; uint multip = initialPrice * factor; uint result = initialPrice - multip / increasePerBlockDiv; require (result<=initialPrice); return result; }
6,711,669
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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 = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev 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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.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 {} uint256[44] private __gap; } // 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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/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 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Digital art collectible metaverse * @author NFT Legends team **/ contract Collection is ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable { event NameChange(uint256 indexed index, string newName); event SkillChange(uint256 indexed index, uint256 newSkill); event DnaChange(uint256 indexed index, uint256 newDna); event Buy(address indexed _from, uint256 nfts, address referral); // each token has its own attributes: Name, Skill and DNA // Name is the symbolic string, that can be changed over time mapping(uint256 => string) private _tokenName; // Skill is a numeric value that represents character's experience mapping(uint256 => uint256) private _tokenSkill; // DNA is 256-bit map where unique token attributes encoded mapping(uint256 => uint256) private _tokenDna; // when sale is active, anyone is able to buy the token bool public saleActive; using SafeMath for uint256; using Strings for uint256; // The token purchase price depends on how early you buy the character // (i.e. sequential number of the purchase) struct SaleStage { uint256 startTokensBought; uint256 endTokensBought; uint256 weiPerToken; } // All the tokens are grouped in batches. Batch is basically IPFS folder (DAG) // that stores token descriptions and images. It tokenId falls into batch, the // tokenURI = batch.baseURI + "/" + tokenId. // All the batches have the same rarity parameter. struct Batch { uint256 startBatchTokenId; uint256 endBatchTokenId; string baseURI; uint256 rarity; } // Arrays that store configured batches and saleStages Batch[] internal _batches; SaleStage[] internal _saleStages; // Maximum allowed tokenSupply boundary. Can be extended by adding new stages. uint256 internal _maxTotalSupply; // Max NFTs that can be bought at once. To avoid gas overspending. uint256 public maxPurchaseSize; // If tokenId doesn't match any configured batch, defaultURI parameters are used. string internal _defaultUri; uint256 internal _defaultRarity; string internal _defaultName; uint256 internal _defaultSkill; // Roles that can modify individual characteristics bytes32 public constant NAME_SETTER_ROLE = keccak256("NAME_SETTER_ROLE"); bytes32 public constant SKILL_SETTER_ROLE = keccak256("SKILL_SETTER_ROLE"); bytes32 public constant DNA_SETTER_ROLE = keccak256("DNA_SETTER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // Received funds (native Ether or BNB) get transferred to Vault address address payable public vault; function initialize() public initializer { __ERC721_init("CyberPunk", "A-12"); __ERC721Enumerable_init(); __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(NAME_SETTER_ROLE, _msgSender()); _setupRole(SKILL_SETTER_ROLE, _msgSender()); _setupRole(DNA_SETTER_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); maxPurchaseSize = 20; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Returns current `_maxTotalSupply` value. */ function maxTotalSupply() public view virtual returns (uint256) { return _maxTotalSupply; } /** * @dev Hook that is called before any token transfer incl. minting */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); // check maxTotalSupply is not exceeded on mint if (from == address(0)) { require(totalSupply() <= _maxTotalSupply, "Collection: maxSupply achieved"); } } /** * @dev Returns the number of configured saleStages (tokensale schedule) * @return current `_saleStages` array length */ function saleStagesLength() public view returns (uint256) { return _saleStages.length; } /** * @dev Returns the saleStage by its index * @param saleStageIndex salestage index in the array * @return info about sale stage */ function getSaleStage(uint256 saleStageIndex) public view returns (SaleStage memory) { require(_saleStages.length > 0, "getSaleStage: no stages"); require(saleStageIndex < _saleStages.length, "Id must be < sale stages length"); return _saleStages[saleStageIndex]; } /** * @dev Returns the length of configured batches * @return current `_batches` array length. */ function batchesLength() public view returns (uint256) { return _batches.length; } /** * @dev Returns all the batches * @return `_batches`. */ function getBatches() public view returns (Batch[] memory) { return _batches; } /** * @dev Returns all sale stages * @return `_saleStages`. */ function getSaleStages() public view returns (SaleStage[] memory) { return _saleStages; } /** * @dev Returns the batch by its index in the array * @param batchIndex batch index * @return Batch info * Note: batch ids can change over time and reorder as the result of batch removal */ function getBatch(uint256 batchIndex) public view returns (Batch memory) { require(_batches.length > 0, "getBatch: no batches"); require(batchIndex < _batches.length, "Id must be < batch length"); return _batches[batchIndex]; } /** * @dev Return batch by given tokenId * @param tokenId token id * @return batch structure */ function getBatchByToken(uint256 tokenId) public view returns (Batch memory) { require(_batches.length > 0, "getBatchByToken: no batches"); for (uint256 i; i < _batches.length; i++) { if (tokenId > _batches[i].endBatchTokenId || tokenId < _batches[i].startBatchTokenId) { continue; } else { return _batches[i]; } } revert("batch doesn't exist"); } /** * @dev IPFS address that stores JSON with token attributes * Tries to find it by batch first. If token has no batch, returns defaultUri. * @param tokenId id of the token * @return string with ipfs address to json with token attribute * or URI for default token if token doesn`t exist */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_batches.length > 0, "tokenURI: no batches"); for (uint256 i; i < _batches.length; i++) { if (tokenId > _batches[i].endBatchTokenId || tokenId < _batches[i].startBatchTokenId) { continue; } else { return string(abi.encodePacked(_batches[i].baseURI, "/", tokenId.toString(), ".json")); } } return _defaultUri; } /** * @notice Creates the new batch for given token range * @param startTokenId index of the first batch token * @param endTokenId index of the last batch token * @param baseURI ipfs batch URI * @param rarity batch rarity * Note: batch ids can change over time and reorder as the result of batch removal */ function addBatch( uint256 startTokenId, uint256 endTokenId, string memory baseURI, uint256 rarity ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _batchesLength = _batches.length; require(startTokenId <= endTokenId, "startId must be <= than EndId"); if (_batchesLength > 0) { for (uint256 i; i < _batchesLength; i++) { // if both bounds are lower or higher than iter batch if ( (startTokenId < _batches[i].startBatchTokenId && endTokenId < _batches[i].startBatchTokenId) || (startTokenId > _batches[i].endBatchTokenId && endTokenId > _batches[i].endBatchTokenId) ) { continue; } else { revert("batches intersect"); } } } _batches.push(Batch(startTokenId, endTokenId, baseURI, rarity)); } /** * @notice Update existing batch by its index * @param batchIndex the index of the batch to be changed * @param batchStartId index of the first batch token * @param batchEndId index of the last batch token * @param baseURI ipfs batch URI * @param rarity batch rarity * Note: batch ids can change over time and reorder as the result of batch removal */ function setBatch( uint256 batchIndex, uint256 batchStartId, uint256 batchEndId, string memory baseURI, uint256 rarity ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _batchesLength = _batches.length; require(_batchesLength > 0, "setBatch: batches is empty"); require(batchStartId <= batchEndId, "startId must be <= than EndId"); for (uint256 i; i < _batchesLength; i++) { if (i == batchIndex) { continue; } else { // if both bounds are lower or higher than iter batch if ( (batchStartId < _batches[i].startBatchTokenId && batchEndId < _batches[i].startBatchTokenId) || (batchStartId > _batches[i].endBatchTokenId && batchEndId > _batches[i].endBatchTokenId) ) { continue; } else { revert("batches intersect"); } } } _batches[batchIndex].startBatchTokenId = batchStartId; _batches[batchIndex].endBatchTokenId = batchEndId; _batches[batchIndex].baseURI = baseURI; _batches[batchIndex].rarity = rarity; } /** * @notice Deletes batch by its id. This reorders the index of the token that was last. * @param batchIndex the index of the batch to be deteted */ function deleteBatch(uint256 batchIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_batches.length > batchIndex, "index out of batches length"); _batches[batchIndex] = _batches[_batches.length - 1]; _batches.pop(); } /** * @notice Add sale stage (i.e. tokensale schedule) * It takes place at the end of `saleStages array` * @param startTokensBought index of the first batch token * @param endTokensBought index of the last batch token * @param weiPerToken price for token */ function addSaleStage( uint256 startTokensBought, uint256 endTokensBought, uint256 weiPerToken ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(startTokensBought <= endTokensBought, "startTokensBought must be <= than endTokensBought"); require(weiPerToken > 0, "weiPerToken must be non-zero"); uint256 _saleStagesLength = _saleStages.length; if (_saleStagesLength > 0) { for (uint256 i; i < _saleStagesLength; i++) { // if both bounds are lower or higher than iter sale stage if ( (startTokensBought < _saleStages[i].startTokensBought && endTokensBought < _saleStages[i].startTokensBought) || (startTokensBought > _saleStages[i].endTokensBought && endTokensBought > _saleStages[i].endTokensBought) ) { continue; } else { revert("intersection _saleStages"); } } } _saleStages.push(SaleStage(startTokensBought, endTokensBought, weiPerToken)); _maxTotalSupply += endTokensBought - startTokensBought + 1; } /** * @notice Update (rewrite) saleStage properties by index * @param saleStageId index of the first sale stage token * @param startTokensBought index of the first batch token * @param endTokensBought index of the last batch token * @param weiPerToken price for token */ function setSaleStage( uint256 saleStageId, uint256 startTokensBought, uint256 endTokensBought, uint256 weiPerToken ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _saleStagesLength = _saleStages.length; require(_saleStagesLength > 0, "batches is empty"); require(startTokensBought <= endTokensBought, "startId must be <= than EndId"); for (uint256 i; i < _saleStagesLength; i++) { if (i == saleStageId) { continue; } else { // if both bounds are lower or higher than iter sale stage if ( (startTokensBought < _saleStages[i].startTokensBought && endTokensBought < _saleStages[i].startTokensBought) || (startTokensBought > _saleStages[i].endTokensBought && endTokensBought > _saleStages[i].endTokensBought) ) { continue; } else { revert("intersection _saleStages"); } } } SaleStage memory _saleStage = _saleStages[saleStageId]; _maxTotalSupply = _maxTotalSupply - (_saleStage.endTokensBought - _saleStage.startTokensBought + 1) + (endTokensBought - startTokensBought + 1); _saleStages[saleStageId].startTokensBought = startTokensBought; _saleStages[saleStageId].endTokensBought = endTokensBought; _saleStages[saleStageId].weiPerToken = weiPerToken; } /** * @dev Delete sale stage by the given given index * @param saleStageIndex index of the batch to be deleted */ function deleteSaleStage(uint256 saleStageIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_saleStages.length > saleStageIndex, "index out of sale stage length"); SaleStage memory _saleStage = _saleStages[saleStageIndex]; _maxTotalSupply -= _saleStage.endTokensBought - _saleStage.startTokensBought + 1; _saleStages[saleStageIndex] = _saleStages[_saleStages.length - 1]; _saleStages.pop(); } /** * @dev Calculates the total price for the given number of tokens * @param tokens number of tokens to be purchased * @return summary price */ function getTotalPriceFor(uint256 tokens) public view returns (uint256) { require(tokens > 0, "tokens must be more then 0"); uint256 _saleStagesLength = _saleStages.length; uint256 totalSupply = totalSupply(); uint256 iterPrice = 0; uint256 totalPrice = 0; SaleStage memory saleStage; for (uint256 tokenIndex = 0; tokenIndex < tokens; tokenIndex++) { iterPrice = 0; for (uint256 i = 0; i < _saleStagesLength; i++) { saleStage = _saleStages[i]; if (totalSupply > saleStage.endTokensBought || totalSupply < saleStage.startTokensBought) continue; iterPrice += saleStage.weiPerToken; } if (iterPrice == 0) { revert("saleStage doesn't exist"); } totalPrice += iterPrice; totalSupply += 1; } return totalPrice; } /** * @dev Method to randomly mint desired number of NFTs * @param to the address where you want to transfer tokens * @param nfts the number of tokens to be minted */ function _mintMultiple(address to, uint256 nfts) internal { require(totalSupply() < _maxTotalSupply, "Sale has already ended"); require(nfts > 0, "nfts cannot be 0"); require(totalSupply().add(nfts) <= _maxTotalSupply, "Exceeds _maxTotalSupply"); for (uint256 i = 0; i < nfts; i++) { uint256 mintIndex = _getRandomAvailableIndex(); _safeMint(to, mintIndex); } } /** * @dev Mints a specific token (with known id) to the given address * @param to the receiver * @param mintIndex the tokenId to mint */ function mint(address to, uint256 mintIndex) public onlyRole(MINTER_ROLE) { _safeMint(to, mintIndex); } /** * @dev Public method to randomly mint desired number of NFTs * @param to the receiver * @param nfts the number of tokens to be minted */ function mintMultiple(address to, uint256 nfts) public onlyRole(MINTER_ROLE) { _mintMultiple(to, nfts); } /** * @dev Method to purchase and random available NFTs. * @param nfts the number of tokens to buy * @param referral the address of referral who invited the user to the platform */ function buy(uint256 nfts, address referral) public payable { require(saleActive, "Sale is not active"); require(nfts <= maxPurchaseSize, "Can not buy > maxPurchaseSize"); require(getTotalPriceFor(nfts) == msg.value, "Ether value sent is not correct"); emit Buy(msg.sender, nfts, referral); vault.transfer(msg.value); _mintMultiple(msg.sender, nfts); } /** * @dev Returns the (pseudo-)random token index free of owner. * @return available token index */ function _getRandomAvailableIndex() internal view returns (uint256) { uint256 index = (uint256( keccak256( abi.encodePacked( block.timestamp, /* solhint-disable not-rely-on-time */ gasleft(), blockhash(block.number - 1) ) ) ) % _maxTotalSupply); while (_exists(index)) { index += 1; if (index >= _maxTotalSupply) { index = 0; } } return index; } /** * @dev Returns rarity of the NFT by token Id * @param tokenId id of the token * @return rarity */ function getRarity(uint256 tokenId) public view returns (uint256) { require(_batches.length > 0, "getBatchByToken: no batches"); for (uint256 i; i < _batches.length; i++) { if (tokenId > _batches[i].endBatchTokenId || tokenId < _batches[i].startBatchTokenId) { continue; } else { return _batches[i].rarity; } } return _defaultRarity; } /** * @dev Returns name of the NFT at index * @param index token id * @return NFT name */ function getName(uint256 index) public view returns (string memory) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); bytes memory _tokenWeight = bytes(_tokenName[index]); if (_tokenWeight.length == 0) { return _defaultName; } return _tokenName[index]; } /** * @dev Returns skill of the NFT at index * @param index token id * @return NFT skill */ function getSkill(uint256 index) public view returns (uint256) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); if (_tokenSkill[index] == 0) { return _defaultSkill; } return _tokenSkill[index]; } /** * @dev Returns individual DNA of the NFT at index * @param index token id * @return NFT DNA */ function getDna(uint256 index) public view returns (uint256) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); return _tokenDna[index]; } /** * @dev Start tokensale process */ function start() public onlyRole(DEFAULT_ADMIN_ROLE) { require(bytes(_defaultUri).length > 0, "_defaultUri is undefined"); require(vault != address(0), "Vault is undefined"); saleActive = true; } /** * @dev Stop tokensale */ function stop() public onlyRole(DEFAULT_ADMIN_ROLE) { saleActive = false; } /** * @dev Set or change individual token name */ function setName(uint256 index, string memory newName) public onlyRole(NAME_SETTER_ROLE) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); _tokenName[index] = newName; emit NameChange(index, newName); } /** * @dev Set or change individual token skill */ function setSkill(uint256 index, uint256 newSkill) public onlyRole(SKILL_SETTER_ROLE) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); _tokenSkill[index] = newSkill; emit SkillChange(index, newSkill); } /** * @dev Set or change individual token DNA */ function setDna(uint256 index, uint256 newDna) public onlyRole(DNA_SETTER_ROLE) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); _tokenDna[index] = newDna; emit DnaChange(index, newDna); } /** * @dev Set max purchase size (to avoid gas overspending) */ function setMaxPurchaseSize(uint256 newPurchaseSize) public onlyRole(DEFAULT_ADMIN_ROLE) { maxPurchaseSize = newPurchaseSize; } /** * @dev Set defaultUri */ function setDefaultUri(string memory uri) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultUri = uri; } /** * @dev Set vault * @param newVault address to receive ethers */ function setVault(address payable newVault) public onlyRole(DEFAULT_ADMIN_ROLE) { vault = newVault; } /** * @dev Set defaultRarity * @param rarity new default rarity */ function setDefaultRarity(uint256 rarity) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultRarity = rarity; } /** * @dev Set default name. * @param name new default name */ function setDefaultName(string memory name) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultName = name; } /** * @dev Set default skill. * @param skill new default name */ function setDefaultSkill(uint256 skill) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultSkill = skill; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "./Collection.sol"; contract NFTStaking is OwnableUpgradeable, ERC721HolderUpgradeable { // user deposits are recorded in StakeInfo[] stakes struct struct StakeInfo { // staked is true if token is staked and hasn't been unstaked. // After user claims his stake back, `staked` becomes false bool staked; // address of staked token's owner address stakerAddress; // time of start staking token uint256 lastUpdateTime; // totalYield is a total value of rewards for the given stake. // user is able to withdraw yield. uint256 totalYield; // The amount of yield user already harvested uint256 harvestedYield; } // If stakesOpen == true, the contract is operational and accepts new stakes. // Otherwise it allows just harvesting and unstaking. bool public stakesOpen; // Token used for rewards IERC20 public nftlToken; // The token accepted for staking Collection public heroesToken; uint256 internal constant WELCOME_BONUS_TIME = 365 * 24 * 60 * 60; // struccture that stores the records of users' stakes mapping(uint256 => StakeInfo) public stakes; // struccture that stores the records of users' staked tokens mapping(address => uint256[]) public stakedTokens; // Base reward that staker will receive for his stake uint256 public baseRewardPerSecond; event Stake(address indexed user, uint256 indexed tokenId); event Unstake(address indexed user, uint256 indexed tokenId); event Harvest(address indexed user, uint256 indexed tokenId, uint256 amount); /** * @dev the constructor arguments: * @param _nftlAddress address of token - the same used to pay rewards * @param _heroesAddress address of token - the same accepted for staking */ function initialize(address _nftlAddress, address _heroesAddress) public initializer { require(_nftlAddress != address(0), "Empty NFTL token address"); require(_heroesAddress != address(0), "Empty heroes address"); nftlToken = IERC20(_nftlAddress); heroesToken = Collection(_heroesAddress); __Ownable_init(); } /** * @dev start accepting new stakes. Called only by the owner */ function start() public onlyOwner { require(!stakesOpen, "Stakes are open already"); stakesOpen = true; } /** * @dev stop accepting new stakes. Called only by the owner */ function stop() public onlyOwner { require(stakesOpen, "Stakes are stopped already"); stakesOpen = false; } /** * @dev set base reward for tokens * @param _baseRewardPerSecond base reward in second */ function setBaseRewardPerSecond(uint256 _baseRewardPerSecond) public onlyOwner { baseRewardPerSecond = _baseRewardPerSecond; } /** * @dev the owner is able to withdraw excess tokens * @param _to address who will receive the funds * @param _amount amount of tokens in atto (1e-18) units */ function withdrawNftl(address _to, uint256 _amount) public onlyOwner { require(_to != address(0), "Empty receiver address"); require(_amount > 0, "Zero amount"); require(nftlToken.balanceOf(address(this)) >= _amount, "Not enough tokens"); nftlToken.transfer(_to, _amount); } /** * @dev submit the stake * @param _tokenId id of hero token */ function stake(uint256 _tokenId) external { require(stakesOpen, "stake: not open"); stakes[_tokenId].staked = true; stakes[_tokenId].stakerAddress = msg.sender; stakes[_tokenId].lastUpdateTime = block.timestamp; // stakers get welcome bonus for their first stake if (stakes[_tokenId].totalYield == 0) { stakes[_tokenId].totalYield = WELCOME_BONUS_TIME * getTokenRewardPerSecond(_tokenId); } stakedTokens[msg.sender].push(_tokenId); emit Stake(msg.sender, _tokenId); heroesToken.safeTransferFrom(msg.sender, address(this), _tokenId); } /** * @dev withdraw the user's staked token * @param _tokenId id of hero token */ function unstake(uint256 _tokenId) external { require(msg.sender == stakes[_tokenId].stakerAddress, "Sender is not staker"); require(stakes[_tokenId].staked, "Unstaked already"); _updateYield(_tokenId); stakes[_tokenId].staked = false; stakes[_tokenId].stakerAddress = address(0); // Since `delete` Solidity operator leaves zeroes at the deleted index and // doesn'd decrease array length. // To actually drop data and shorten the list, we copy last item to the index // of removed value (overwriting it) then pop last element to decrease array size for (uint256 i = 0; i < stakedTokens[msg.sender].length; ++i) { if (stakedTokens[msg.sender][i] == _tokenId) { uint256 lastElementIndex = stakedTokens[msg.sender].length - 1; stakedTokens[msg.sender][i] = stakedTokens[msg.sender][lastElementIndex]; stakedTokens[msg.sender].pop(); break; } } emit Unstake(msg.sender, _tokenId); _calculateAndTransferHarvest(_tokenId); heroesToken.safeTransferFrom(address(this), msg.sender, _tokenId); } /** * @dev harvest accumulated rewards. Can be called many times. * @param _tokenId Id of the token to be harvested */ function harvest(uint256 _tokenId) external { address currentTokenHolder = heroesToken.ownerOf(_tokenId); if (currentTokenHolder == address(this)) { // token is on staking contract, so we need to check it was indeed staked by msg.sender require(msg.sender == stakes[_tokenId].stakerAddress, "Sender is not staker"); _updateYield(_tokenId); } else { // token is on another address, so we need to check msg.sender is its owner require(msg.sender == currentTokenHolder, "Sender is not holder"); } require(stakes[_tokenId].totalYield > stakes[_tokenId].harvestedYield, "No harvestableYield"); _calculateAndTransferHarvest(_tokenId); } /** * @dev return the array of staked token IDs * @param _staker address of token staker * @return stakedTokens array of staked token IDs */ function getStakedTokens(address _staker) public view returns (uint256[] memory) { return stakedTokens[_staker]; } /** * @dev return unaccounted reward that is not reflected in the contract state * for staked tokens this function returns value that increments each block. * For tokens that are not staked it returns 0 * @param _tokenId index of the token * @return rewardSinceLastUpdate reward tokens that were accumulated sinceLastUpdate */ function getRewardSinceLastUpdate(uint256 _tokenId) public view returns (uint256 rewardSinceLastUpdate) { rewardSinceLastUpdate = 0; if (stakes[_tokenId].staked) { uint256 secondsStaked = block.timestamp - stakes[_tokenId].lastUpdateTime; rewardSinceLastUpdate = getTokenRewardPerSecond(_tokenId) * secondsStaked; } } /** * @dev get the individual stake parameters of the user's staked token * @param _tokenId token stake index * @return staked the status of stake * @return stakerAddress address of staker * @return lastUpdateTime time of start staking * @return totalYield entire yield for the stake * @return harvestedYield The part of yield user harvested already */ function getStake(uint256 _tokenId) external view returns ( bool staked, address stakerAddress, uint256 lastUpdateTime, uint256 totalYield, uint256 harvestedYield ) { StakeInfo memory _stake = stakes[_tokenId]; staked = _stake.staked; stakerAddress = _stake.stakerAddress; lastUpdateTime = _stake.lastUpdateTime; totalYield = _stake.totalYield + getRewardSinceLastUpdate(_tokenId); harvestedYield = _stake.harvestedYield; } /** * @dev calculate reward speed for the given tokenId * @param _tokenId token id * @return rewardPerSecond in atto tokens per second */ function getTokenRewardPerSecond(uint256 _tokenId) public view returns (uint256 rewardPerSecond) { rewardPerSecond = baseRewardPerSecond * heroesToken.getRarity(_tokenId); } /** * @dev Update accumulated reward for staked token * @param _tokenId token id */ function _updateYield(uint256 _tokenId) internal { require(stakes[_tokenId].staked, "Token not staked"); stakes[_tokenId].totalYield += getRewardSinceLastUpdate(_tokenId); stakes[_tokenId].lastUpdateTime = block.timestamp; } /** * @dev Calculate yield amount, emit Harvest event and pay nftl tokens * @param _tokenId token id */ function _calculateAndTransferHarvest(uint256 _tokenId) internal { uint256 amount = stakes[_tokenId].totalYield - stakes[_tokenId].harvestedYield; stakes[_tokenId].harvestedYield = stakes[_tokenId].totalYield; emit Harvest(msg.sender, _tokenId, amount); nftlToken.transfer(msg.sender, amount); } }
Add sale stage (i.e. tokensale schedule) It takes place at the end of `saleStages array` startTokensBought index of the first batch token endTokensBought index of the last batch token weiPerToken price for token/ if both bounds are lower or higher than iter sale stage
function addSaleStage( uint256 startTokensBought, uint256 endTokensBought, uint256 weiPerToken ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(startTokensBought <= endTokensBought, "startTokensBought must be <= than endTokensBought"); require(weiPerToken > 0, "weiPerToken must be non-zero"); uint256 _saleStagesLength = _saleStages.length; if (_saleStagesLength > 0) { for (uint256 i; i < _saleStagesLength; i++) { if ( (startTokensBought < _saleStages[i].startTokensBought && endTokensBought < _saleStages[i].startTokensBought) || (startTokensBought > _saleStages[i].endTokensBought && endTokensBought > _saleStages[i].endTokensBought) ) { continue; revert("intersection _saleStages"); } } } _saleStages.push(SaleStage(startTokensBought, endTokensBought, weiPerToken)); _maxTotalSupply += endTokensBought - startTokensBought + 1; }
11,682,380
pragma solidity ^0.4.14; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function ownerOf(uint256 _tokenId) external view returns (address owner); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); } /// @title The external contract that is responsible for generating metadata for the Artworks, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) internal tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), uint256(_auction.startedAt) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. //(Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Ownable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(INTERFACE_SIGNATURE_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Clock auction modified for sale of artworks /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of artwork sales uint256 public artworkSaleCount; uint256[5] public lastArtworkSalePrices; uint256 internal value; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastArtworkSalePrices[artworkSaleCount % 5] = price; value += price; artworkSaleCount++; } } function averageArtworkSalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastArtworkSalePrices[i]; } return sum / 5; } function getValue() external view returns (uint256) { return value; } } contract ArtworkAccessControl { // This facet controls access control for CryptoArtworks. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the ArtworkCore constructor. // // - The CFO: The CFO can withdraw funds from ArtworkCore and its auction contracts. // // - The COO: The COO can release artworks to auction, and mint promo arts. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoArtworks. Holds all common structs, events and base variables. /// @dev See the ArtworkCore contract documentation to understand how the various contract facets are arranged. contract ArtworkBase is ArtworkAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new artwork comes into existence. This obviously /// includes any time a artwork is created through the giveBirth method, but it is also called /// when a new artwork is created. event Birth(address owner, uint256 artworkId, string name, string author, uint32 series); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a artwork /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Artwork struct. Every art in CryptoArtworks is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Artwork { // The timestamp from the block when this artwork came into existence. uint64 birthTime; // The name of the artwork string name; string author; //sometimes artists produce a series of paintings with the same name //in order to separate them from each other by introducing a variable series. //Series with number 0 means that the picture was without series uint32 series; } // An approximation of currently how many seconds are in between blocks. // uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Artwork struct for all Artworks in existence. The ID /// of each artwork is actually an index into this array. /// Artwork ID 0 is invalid... ;-) Artwork[] internal artworks; /// @dev A mapping from artwork IDs to the address that owns them. All artworks have /// some valid owner address. mapping (uint256 => address) public artworkIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) internal ownershipTokenCount; /// @dev A mapping from artworkIDs to an address that has been approved to call /// transferFrom(). Each Artwork can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public artworkIndexToApproved; /// @dev The address of the ClockAuction contract that handles sales of Artworks. This /// same contract handles both peer-to-peer sales as well as the initial sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev Assigns ownership of a specific Artwork to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of artworks is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership artworkIndexToOwner[_tokenId] = _to; // When creating new artworks _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete artworkIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new artwork and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _id The artwork's genetic code. /// @param _owner The inital owner of this art, must be non-zero (except for ID 0) // The timestamp from the block when this artwork came into existence. uint64 internal birthTime; string internal author; // The name of the artwork string internal name; uint32 internal series; function _createArtwork(string _name, string _author, uint32 _series, address _owner ) internal returns (uint) { Artwork memory _artwork = Artwork({ birthTime: uint64(now), name: _name, author: _author, series: _series}); uint256 newArtworkId = artworks.push(_artwork) - 1; // It's probably never going to happen, 4 billion artworks is A LOT, but // let's just be 100% sure we never let this happen. require(newArtworkId == uint256(uint32(newArtworkId))); // emit the birth event Birth(_owner, newArtworkId, _artwork.name, _artwork.author, _series); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newArtworkId); return newArtworkId; } } // Creates dictionary with unique keys, if the key is already used then its value will be true. // It is not possible to create a duplicate. contract ArtworkUnique { //mapping with unique key mapping (bytes32 => bool) internal uniqueArtworks; //Creates a unique key based on the artwork name, author, and series function getUniqueKey(string name, string author, uint32 _version) internal pure returns(bytes32) { string memory version = _uintToString(_version); string memory main = _strConcat(name, author, version, "$%)"); string memory lowercased = _toLower(main); return keccak256(lowercased); } //https://gist.github.com/thomasmaclean/276cb6e824e48b7ca4372b194ec05b97 //transform to lowercase function _toLower(string str) internal pure returns (string) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((bStr[i] >= 65) && (bStr[i] <= 90)) { // So we add 32 to make it lowercase bLower[i] = bytes1(int(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } //creates a unique key from all variables function _strConcat(string _a, string _b, string _c, string _separator) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_separator); bytes memory _bc = bytes(_b); bytes memory _bd = bytes(_separator); bytes memory _be = bytes(_c); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } //convert uint To String function _uintToString(uint v) internal pure returns (string) { bytes32 data = _uintToBytes(v); return _bytes32ToString(data); } /// title String Utils - String utility functions /// @author Piper Merriam - <pipermerriam@gmail.com> ///https://github.com/pipermerriam/ethereum-string-utils function _uintToBytes(uint v) private pure returns (bytes32 ret) { if (v == 0) { ret = "0"; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; } } return ret; } function _bytes32ToString(bytes32 x) private pure 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 The facet of the CryptoArtworks core contract that manages ownership, ERC-721 (draft) compliant. /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the ArtworkCore contract documentation to understand how the various contract facets are arranged. contract ArtworkOwnership is ArtworkBase, ArtworkUnique, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoArtworks"; string public constant SYMBOL = "CA"; // The contract that will return artwork metadata ERC721Metadata public erc721Metadata; bytes4 private constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 private constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /// @notice Grant another address the right to transfer a specific Artwork via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Artwork that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Artwork owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Artwork to be transfered. /// @param _to The address that should take ownership of the Artwork. Can be any address, /// including the caller. /// @param _tokenId The ID of the Artwork to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any artworks (except very briefly // after a artwork is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Transfers a Artwork to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoArtworks specifically) or your Artwork may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Artwork to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Artworks (except very briefly // after a artwork is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of artworks // through the allow + transferFrom flow. require(_to != address(saleAuction)); // You can only send your own artwork. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Returns a list of all Artwork IDs assigned to an address. /// @param _owner The owner whose Artworks we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Artwork array looking for arts 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 totalArts = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all arts have IDs starting at 1 and increasing // sequentially up to the totalArt count. uint256 artworkId; for (artworkId = 1; artworkId <= totalArts; artworkId++) { if (artworkIndexToOwner[artworkId] == _owner) { result[resultIndex] = artworkId; resultIndex++; } } return result; } } /// @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 == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721)); } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Artwork whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } /// @notice Returns the address currently assigned ownership of a given Artwork. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = artworkIndexToOwner[_tokenId]; require(owner != address(0)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } /// @notice Returns the total number of Artworks currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return artworks.length - 1; } /// @notice Returns the number of Artworks owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Artwork. /// @param _claimant the address we are validating against. /// @param _tokenId artwork id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return artworkIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Artwork. /// @param _claimant the address we are confirming artwork is approved for. /// @param _tokenId artwork id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return artworkIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Artworks on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { artworkIndexToApproved[_tokenId] = _approved; } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for (; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } } /// @title Handles creating auctions for sale artworks. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract ArtworkAuction is ArtworkOwnership { // @notice The auction contract variables are defined in ArtworkBase to allow // us to refer to _createArtworkthem in ArtworkOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for created artworks and p2p sale of artworks. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - //https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Put a artwork up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _artworkId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If artwork is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _artworkId)); _approve(_artworkId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the artwork. saleAuction.createAuction( _artworkId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Transfers the balance of the sale auction contract /// to the ArtworkCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); } } /// @title all functions related to creating artworks contract ArtworkMinting is ArtworkAuction { // Limits the number of arts the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant CREATION_LIMIT = 450000; // Constants for auctions. uint256 public constant ARTWORK_STARTING_PRICE = 10 finney; uint256 public constant ARTWORK_AUCTION_DURATION = 1 days; // Counts the number of arts the contract owner has created. uint256 public promoCreatedCount; uint256 public artsCreatedCount; /// @dev we can create promo artworks, up to a limit. Only callable by COO /// @param _owner the future owner of the created artworks. Default to contract COO function createPromoArtwork(string _name, string _author, uint32 _series, address _owner) external onlyCOO { bytes32 uniqueKey = getUniqueKey(_name, _author, _series); (require(!uniqueArtworks[uniqueKey])); if (_series != 0) { bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0); (require(!uniqueArtworks[uniqueKeyForZero])); } address artworkOwner = _owner; if (artworkOwner == address(0)) { artworkOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createArtwork(_name, _author, _series, artworkOwner); uniqueArtworks[uniqueKey] = true; } /// @dev Creates a new artwork with the given name and author and /// creates an auction for it. function createArtworkAuction(string _name, string _author, uint32 _series) external onlyCOO { bytes32 uniqueKey = getUniqueKey(_name, _author, _series); (require(!uniqueArtworks[uniqueKey])); require(artsCreatedCount < CREATION_LIMIT); if (_series != 0) { bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0); (require(!uniqueArtworks[uniqueKeyForZero])); } uint256 artworkId = _createArtwork(_name, _author, _series, address(this)); _approve(artworkId, saleAuction); uint256 price = _computeNextArtworkPrice(); saleAuction.createAuction( artworkId, price, 0, ARTWORK_AUCTION_DURATION, address(this) ); artsCreatedCount++; uniqueArtworks[uniqueKey] = true; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextArtworkPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageArtworkSalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < ARTWORK_STARTING_PRICE) { nextPrice = ARTWORK_STARTING_PRICE; } return nextPrice; } } /** * The contractName contract does this and that... */ contract ArtworkQuestions is ArtworkMinting { string private constant QUESTION = "What is the value? Nothing is "; string public constant MAIN_QUESTION = "What is a masterpiece? "; function getQuestion() public view returns (string) { uint256 value = saleAuction.getValue(); string memory auctionValue = _uintToString(value); return _strConcat(QUESTION, auctionValue, "", ""); } } /// @title CryptoArtworks: Collectible arts on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoArtworks contract, keeps track of artworks so they don't wander around and get lost. contract ArtworkCore is ArtworkQuestions { // This is the main CryptoArtworks contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // artwork ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - ArtworkBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - ArtworkAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - ArtworkOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - ArtworkAuctions: Here we have the public methods for auctioning or bidding on arts. // The actual auction functionality is handled in contract // for sales, while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - ArtworkMinting: This final facet contains the functionality we use for creating new arts. // We can make up to 5000 "promo" arts that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 450k arts. // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoArtworks smart contract instance. function ArtworkCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the art _createArtwork("none", "none", 0, address(0)); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) ); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = this.balance; cfoAddress.send(balance); } /// @notice Returns all the relevant information about a specific artwork. /// @param _id The ID of the artwork of interest. function getArtwork(uint256 _id) external view returns ( uint256 birthTime, string name, string author, uint32 series ) { Artwork storage art = artworks[_id]; birthTime = uint256(art.birthTime); name = string(art.name); author = string(art.author); series = uint32(art.series); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } }
Internal utility functions: These functions all assume that their input arguments are valid. We leave it to public methods to sanitize their inputs and follow the required logic. Checks if a given address is the current owner of a particular Artwork. _claimant the address we are validating against. _tokenId artwork id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return artworkIndexToOwner[_tokenId] == _claimant; }
418,733
./full_match/1/0x239A4bF81759774bdC3D0a0244E56A667fdB81bf/sources/contracts/Treasury.sol
Return list of cTokens
function cTokenList() external view returns (address[] memory) { return _cTokenList.values(); }
9,807,775
pragma solidity ^0.5.0; import "./Token.sol"; contract EthSwap { using SafeMath for uint256; string public name = "EthSwap Instant Exchange"; Token public token; uint256 public rate = 100; event TokensPurchased( address buyer, address from, address token, uint256 amount, uint256 rate ); event TokensSold( address seller, address to, address token, uint256 amount, uint256 rate ); constructor(Token _token) public { token = _token; } function buyTokens() public payable { // Sets the token exchange rate uint256 tokenAmount = msg.value.mul(rate); // Requires there be enough tokens available for purchase require(token.balanceOf(address(this)) >= tokenAmount, 'All tokens have been purchased!'); // Transfers purchased tokens to buyer token.transfer(msg.sender, tokenAmount); // Emits TokensPurchased event emit TokensPurchased(msg.sender, address(this), address(token), tokenAmount, rate); } function sellTokens(uint256 _amount) public payable { // Calculate Eth exchange rate uint256 ethAmount = _amount.div(rate); // Requires there be enough Eth available for exchange require(address(this).balance >= ethAmount, 'No Eth balance remaining!'); // Transfers sold tokens to exchange token.transferFrom(msg.sender, address(this), _amount); // Transfers Eth to user msg.sender.transfer(ethAmount); // Emits TokensSold event emit TokensSold(msg.sender, address(this), address(token), _amount, rate); } }
Calculate Eth exchange rate Requires there be enough Eth available for exchange Transfers sold tokens to exchange Transfers Eth to user Emits TokensSold event
function sellTokens(uint256 _amount) public payable { uint256 ethAmount = _amount.div(rate); require(address(this).balance >= ethAmount, 'No Eth balance remaining!'); token.transferFrom(msg.sender, address(this), _amount); msg.sender.transfer(ethAmount); emit TokensSold(msg.sender, address(this), address(token), _amount, rate); }
13,025,710
/* MIT License Copyright (c) 2017 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.6; import "oraclizeLib.sol"; import "FixedToDynamic.sol"; import "idOracleLib.sol"; contract OraclesPipeAPI { function sendPipe(bytes _pipe) external; } contract DigitalIdConnector { address public owner_; address public database_; //permanent address public logic_; address public oracle_; address public walletOracle_; address public interface_; address public coster_; modifier onlyOwner() { if (msg.sender != owner_) throw; _; } event LOG_updatedDatabase(address indexed addr); event LOG_updatedLogic(address indexed addr); event LOG_updatedOracle(address indexed addr); event LOG_updatedWalletOracle(address indexed addr); event LOG_updatedInterface(address indexed addr); event LOG_updatedCostEstimator(address indexed addr); function DigitalIdConnector() { owner_ = msg.sender; } function updateDatabaseAddress(address _database) external onlyOwner { database_ = _database; LOG_updatedDatabase(_database); } function updateLogicAddress(address _logic) external onlyOwner { logic_ = _logic; LOG_updatedLogic(_logic); } function updateOracleAddress(address _oracle) external onlyOwner { oracle_ = _oracle; LOG_updatedOracle(_oracle); } function updateWalletOracleAddress(address _walletOracle) external onlyOwner { walletOracle_ = _walletOracle; LOG_updatedWalletOracle(_walletOracle); } function updateInterfaceAddress(address _interface) external onlyOwner { interface_ = _interface; LOG_updatedInterface(_interface); } function updateCosterAddress(address _coster) external onlyOwner { coster_ = _coster; LOG_updatedInterface(_coster); } } contract DigitalIdInterface { DigitalIdConnector public connector_; DigitalIdLogic public logic_; DigitalIdOracle public oracle_; modifier checkLogic() { if (logic_ != connector_.logic_()) { logic_ = DigitalIdLogic(connector_.logic_()); } _; } modifier checkOracle() { if (oracle_ != connector_.oracle_()) { oracle_ = DigitalIdOracle(connector_.oracle_()); } _; } function DigitalIdInterface(address _connector) { connector_ = DigitalIdConnector(_connector); } function linkEID(bytes _crt, bytes _sig) external checkLogic payable { logic_.linkEID.value(msg.value)(msg.sender, _crt, _sig); } function retryFailedCallback() external checkOracle payable { oracle_.retryCallback.value(msg.value)(msg.sender); // add event resume } function retryFailedCallback(address _linked) external checkOracle payable { oracle_.retryCallback.value(msg.value)(_linked); // add event resume } function requestOCSPCheck(address _user) external checkOracle payable { oracle_.requestPostOCSPCheck.value(msg.value)(_user, msg.sender); } function revokeOwnAddress() external { logic_.revocationRequest(msg.sender); } function getEIDCheckCost() external constant returns (uint) { return DigitalIdCostEstimator(connector_.coster_()).expectedOracleCosts(false); } function getEIDCheckCostWithSHA1() external constant returns (uint) { return DigitalIdCostEstimator(connector_.coster_()).expectedOracleCosts(true); } } contract DigitalIdDatabase { struct PublicKey { bytes mod; bytes exp; } struct Certificate { // uint id; string commonName; PublicKey publicKey; bytes crtSignature; byte crtSigAlgorithm; // 05 = sha1, // 0b = sha256 uint40 serialNumber; bytes20 parentId; bool validated; bool ocspRevoked; uint ocspLastTimestamp; uint ocspLastBlock; uint txNonce; bytes bodyHash; } struct Resident { bytes32 certificateHash; bytes usrSignature; uint8 validityLevel; bool userRevoked; } address public owner_; mapping (bytes32 => Certificate) private certificate_; mapping (address => Resident) private eResident_; mapping (bytes20 => bytes) public parentCrts_; DigitalIdConnector public connector_; DigitalIdLogic public logic_; DigitalIdOracle public oracle_; modifier onlyOwner() { if (msg.sender != owner_) throw; _; } modifier onlyLogic() { if (msg.sender != connector_.logic_()) throw; _; } modifier onlyOracle() { if (msg.sender != connector_.oracle_()) throw; _; } modifier onlyWalletOracle() { if (msg.sender != connector_.walletOracle_()) throw; _; } modifier checkLogic() { if (logic_ != connector_.logic_()) { logic_ = DigitalIdLogic(connector_.logic_()); } _; } modifier checkOracle() { if (oracle_ != connector_.oracle_()) { oracle_ = DigitalIdOracle(connector_.oracle_()); } _; } function DigitalIdDatabase(address _connector) { owner_ = msg.sender; connector_ = DigitalIdConnector(_connector); } /* add these manually after the fact as owner function whiteListParents() private { // using ones needed as specified by // https://www.sk.ee/en/repository/certs/ // ESTEID-SK 2011 parentCrts_[0x7B6AF255505CB8D97A088741AEFAA22B3D5B5776] = hex'b3e97c6c661eabfda5dc35ede44a934c3aa990a005d4a73cdcaf8652686661ffb247222a65bcd8bab5b5bf94aeec02246c6fae4accc5913846ae95deba8206c33e06ba914f7b0be0171aeefe0d1397b2d8d43afe9596b1d95409cb9883a4c9ca566b18ccf847d03d9b83c446e4c3de81dff7c6ebd65ba77b3dcba58487053963d222425f184e41a7354c627506ce375046426f87544b204dfdb627aafa1b716c134eeb9cc36c90d0b70e3b8b48250a178907d2b54654af4176209d15a6631c4ca48f08c81b3aa7cb1c9129ee186c9e81f40066f797921603011ed644614faad15508406840180bab3935e35a2d53b2c038da69cb190644239197317b5a6e9e75'; // ESTEID-SK 2015 parentCrts_[0xB3AB88BC99D562A4852A08CDB41D723B83724751] = hex'd281fad4d0f16dd5bd93c9cb035a8668be01eefc9da1dd84c29fd24c1641df012d20908b764a44b12f295df16246ac0356c80619bbbe43df6dae56f92c8ef28bbac8911a2fe4d7ed05d48d3d2539ac08583d086f6594203b045a1dae44cbe05a2c91e62ea6104bd850bd0b02632c2cfb156f3455292b4a460fae22c9ca9d32e065fe75aaddf2ee669a70061d15165b66e2786bff54b447d4d1269a855066c6af838afc3c1e6d0e4f8e1752e3480250dc260bb7cf438bc81fec7e4c2936686faedcca00cf422ba555aa8b0cc6fefc6b7ae3cf02481778509e61fe9f5cbb06cf85a2bec6456e9876a4c8c42eeeac96d9415df006ddf1afe37b7dd555e2732cd1fde4f976c07ecc5b16d6c1d5fb538d3ebfaace00f1087d9c9aeaa864d7c822af9bba86f7780f1e7be5e924a250afed6a1ab9a18208ef02173b9ba714e31fd07f1c1162121536125ffac2954e191085b27d5f1b8a937735f30ca6c0bd66a430f43c8189aa5b2c31e8ae2782336a015b80448634351de22726d21413f029907949b519b59e058b1ea8f84c417f7b40504b5c92d5cb6482ca8033ec1ab5a80e37fbe11c89b37ec817359d0b36668abc724f4c2b46c2c4331e524414cfa55e406a7af4898e42bb30e3aa93cf49ad750acc49b9e45c2b8b6a7e5d3e6dbce09f4799aaa2622ea3e8a2dc6763645270d015eb015653049be7c76b6891ea59c0158674e941'; } */ function onlyOwnerModifier() private onlyOwner { } function onlyLogicModifier() private onlyLogic { } function checkIdOracleModifier() private checkOracle { } function onlyIdOracleModifier() private onlyOracle { } function onlyWalletOracleModifier() private onlyWalletOracle { } function addParent(bytes20 _id, bytes _modulus) external { onlyOwnerModifier(); parentCrts_[_id] = _modulus; } function removeParent(bytes20 _id) external { onlyOwnerModifier(); delete parentCrts_[_id]; } // status: 0x01 = pass // 0x02 = internal error; retryable // 0x03 = sig verification fail // 0x04 = ocsp revoked/unknown status event linkingStatus(address indexed linked, uint level, byte status); event addedEID(address indexed linked, string commonName); function emitLinkEvent(address _linked, uint _level, byte _status) { onlyIdOracleModifier(); linkingStatus(_linked, _level, _status); } event validatingCrtStatus(bytes32 indexed certificateId, uint level, byte status); event addedCrt(bytes32 indexed certificateId, string commonName, uint40 indexed serial); function emitValidatingEvent(bytes32 _crtId, uint _level, byte _status) { onlyWalletOracleModifier(); validatingCrtStatus(_crtId, _level, _status); } function addEID(bytes32 _crtHash, address _address, string _commonName, bytes _usrSig) external { onlyLogicModifier(); eResident_[_address] = Resident(_crtHash, _usrSig, 1, false); addedEID(_address, _commonName); } function addCrt(bytes32 _crtHash, bytes _bodyHash, string _commonName, bytes _mod, bytes _exp, bytes _crtSig, byte _crtSigAlgo, bytes20 _parentId, uint40 _serial) { onlyLogicModifier(); Certificate memory crt = certificate_[_crtHash]; if (crt.validated == false) { certificate_[_crtHash] = Certificate(_commonName, PublicKey(_mod, _exp), _crtSig, _crtSigAlgo, _serial, _parentId, false, false, 0, 0, 0, _bodyHash); addedCrt(_crtHash, _commonName, _serial); } } /*// has to be separated due to stack limit... function addBodyHash(address _address, bytes _hash) external onlyLogic { onlyLogicModifier(); bytes32 crtId = eResident_[_address].certificateHash; if (certificate_[crtId].bodyHash.length == 0) { certificate_[crtId].bodyHash = _hash; } }*/ function appendSHA1BodyHash(address _address, bytes _sha1) external { onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; appendSHA1BodyHash(crtId, _sha1); } function appendSHA1BodyHash(bytes32 _crtId, bytes _sha1) public { if (msg.sender != connector_.walletOracle_() && msg.sender != connector_.oracle_()) { throw; } // allow overwrite in case computation is invalid, as // to not invalidate a cert permanently from db then certificate_[_crtId].bodyHash = _sha1; } function setValidityEID(address _address, uint8 _level) external { onlyIdOracleModifier(); uint currentLevel = eResident_[_address].validityLevel; if (_level < 5 && _level == currentLevel + 1) { eResident_[_address].validityLevel = _level; //initial validation if (_level == 2) { bytes32 crtId = eResident_[_address].certificateHash; certificate_[crtId].validated = true; } } else if (_level == 4 && _level == currentLevel) { return; // This is a successful ocsp check, no state changes } else { throw; } } function setCrtValidated(bytes32 _crtId) external returns (bool) { onlyWalletOracleModifier(); certificate_[_crtId].validated = true; } function incrementCrtTxNonce(bytes32 _crtId, uint _txNonce) external returns (bool) { onlyWalletOracleModifier(); if (_txNonce != certificate_[_crtId].txNonce) return false; certificate_[_crtId].txNonce++; return true; } function ocspUpdateEID(address _address, bool _revoking) external returns (bool) { onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; return ocspUpdate(crtId, _revoking); } function ocspUpdateCrt(bytes32 _crtId, bool _revoking) external returns (bool) { onlyWalletOracleModifier(); return ocspUpdate(_crtId, _revoking); } function ocspUpdate(bytes32 _crtId, bool _revoking) private returns (bool) { certificate_[_crtId].ocspLastTimestamp = block.timestamp; certificate_[_crtId].ocspLastBlock = block.number; // DEBUG - Disable for production certificate_[_crtId].ocspRevoked = _revoking; /* if (_revoking == true) { revokeCrt(_crtId); } */ return true; } // indicates certificate-wide revocation function revokeCrt(bytes32 _crtId) private { certificate_[_crtId].ocspRevoked = true; } // revoke only for address function selfRevokeEID(address _address) external { onlyLogicModifier(); eResident_[_address].userRevoked = true; eResident_[_address].validityLevel = 10; // to indicate self revocation } // in case other contracts fail or get attacked, revocation is still possible function selfDirectRevokeEID() external { if (!isValidatedEID(msg.sender)) throw; eResident_[msg.sender].userRevoked = true; eResident_[msg.sender].validityLevel = 10; } function eResident(address _address) external constant returns (string commonName, bytes mod, bytes exp, bytes crtSignature, bytes usrSignature, bytes bodyHash, bytes20 parentId, byte sigAlgo) { Resident memory res = eResident_[_address]; (commonName, mod, exp, crtSignature, bodyHash, parentId, sigAlgo) = getCrtDetails(res.certificateHash); usrSignature = res.usrSignature; } function eResidentValidity(address _address) external constant returns (uint8 validityLevel, bool isRevoked) { Resident memory res = eResident_[_address]; validityLevel = res.validityLevel; isRevoked = res.userRevoked || certificate_[res.certificateHash].ocspRevoked; } function getCrtDetails(bytes32 _crtId) public constant returns (string commonName, bytes mod, bytes exp, bytes crtSignature, bytes bodyHash, bytes20 parentId, byte sigAlgo) { Certificate memory crt = certificate_[_crtId]; commonName = crt.commonName; mod = crt.publicKey.mod; exp = crt.publicKey.exp; crtSignature = crt.crtSignature; sigAlgo = crt.crtSigAlgorithm; parentId = crt.parentId; bodyHash = crt.bodyHash; } function getCrtStatus(bytes32 _crtId) external constant returns(bool valid, bool revoked, uint ocspLastTimestamp, uint ocspLastBlock) { Certificate memory crt = certificate_[_crtId]; valid = crt.validated; revoked = crt.ocspRevoked; ocspLastTimestamp = crt.ocspLastTimestamp; ocspLastBlock = crt.ocspLastBlock; } function isValidatedEID(address _address) public constant returns (bool valid) { Resident memory res = eResident_[_address]; if (res.validityLevel == 4 && !res.userRevoked && !certificate_[res.certificateHash].ocspRevoked) valid = true; } function getSerialCrt(bytes32 _crtId) external constant returns (uint40) { return certificate_[_crtId].serialNumber; } function getCrtTxNonce(bytes32 _crtId) external constant returns (uint) { return certificate_[_crtId].txNonce; } function getPublicKeyEID(address _address) external constant returns (bytes mod, bytes exp) { bytes32 crtId = eResident_[_address].certificateHash; mod = certificate_[crtId].publicKey.mod; exp = certificate_[crtId].publicKey.exp; } function getParentEID(address _address) external returns (bytes20) { bytes32 crtId = eResident_[_address].certificateHash; return certificate_[crtId].parentId; } function pipeHashEID(address _address) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; oracle_.sendPipe(certificate_[crtId].bodyHash); return true; } function pipeCommonNameEID(address _address) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; oracle_.sendPipe(bytes(certificate_[crtId].commonName)); return true; } function pipeCrtSigEID(address _address) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; oracle_.sendPipe(certificate_[crtId].crtSignature); return true; } function pipeUsrSigEID(address _address) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); oracle_.sendPipe(eResident_[_address].usrSignature); return true; } function pipeUsrModEID(address _address) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; oracle_.sendPipe(certificate_[crtId].publicKey.mod); return true; } function pipeUsrExpEID(address _address) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); bytes32 crtId = eResident_[_address].certificateHash; oracle_.sendPipe(certificate_[crtId].publicKey.exp); return true; } function pipeParentMod(bytes20 _id) external returns (bool) { checkIdOracleModifier(); onlyIdOracleModifier(); oracle_.sendPipe(parentCrts_[_id]); return true; } function pipeSigOCSP(bytes _crt, address _requestingOracle) external checkLogic returns (bool) { onlyLogicModifier(); checkIdOracleModifier(); OraclesPipeAPI(_requestingOracle).sendPipe(_crt); return true; } //|||||||||||||||||||||| function pipeToWalletOracle(bytes32 _crtId, uint _varId) returns (bool) { onlyWalletOracleModifier(); Certificate memory crt = certificate_[_crtId]; bytes memory pipe; if (_varId == 1) pipe = bytes(crt.commonName); else if (_varId == 2) pipe = crt.publicKey.mod; else if (_varId == 3) pipe = crt.publicKey.exp; else if (_varId == 4) pipe = crt.crtSignature; else if (_varId == 5) pipe = crt.bodyHash; else if (_varId == 6) pipe = parentCrts_[crt.parentId]; if (_varId >= 1 && _varId <= 6) { WalletOracle(msg.sender).sendPipe(pipe); return true; } } } contract DigitalIdLogic { struct PublicKey { bytes mod; bytes exp; } // todo add last ocsp check timestamp // todo add function to run post ocsp callback optional struct Certificate { // uint id; string commonName; PublicKey publicKey; bytes signature; byte sigAlgorithm; // 05 = sha1, // 0b = sha256 bytes20 parentId; bytes bodyHash; } //JSON public json_; DigitalIdConnector public connector_; DigitalIdDatabase public database_; DigitalIdOracle public oracle_; modifier onlyInterface() { if (msg.sender != connector_.interface_()) throw; _; } modifier onlyDatabase() { if (msg.sender != connector_.database_()) throw; _; } modifier onlyOracles() { if (msg.sender != connector_.oracle_() && msg.sender != connector_.walletOracle_()) throw; _; } modifier onlyWalletOracle() { if (msg.sender != connector_.walletOracle_()) throw; _; } modifier checkOracle() { if (oracle_ != connector_.oracle_()) { oracle_ = DigitalIdOracle(connector_.oracle_()); } _; } /*modifier checkCrtOracle() { if (oracle_ != connector_.crtOracle_()) { oracle_ = WalletOracle(connector_.crtOracle_()); } _; }*/ function DigitalIdLogic(address _connector) { //OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); connector_ = DigitalIdConnector(_connector); database_ = DigitalIdDatabase(connector_.database_()); } function revocationRequest(address _linked) { if (!database_.isValidatedEID(_linked)) throw; database_.selfRevokeEID(_linked); } function extractCrt(bytes _crt) internal returns (Certificate) { // uint id; bytes memory commonName; bytes memory modulus; bytes memory exponent; bytes20 parentId; byte sigAlgorithm; // 05 = sha1, 0b = sha256 bytes memory signature; bytes memory hash; (commonName, modulus, exponent, parentId) = extractNameKeyParent(_crt); (signature, sigAlgorithm, hash) = extractSigAlgoHash(_crt); return Certificate(string(commonName), PublicKey(modulus, exponent), signature, sigAlgorithm, parentId, hash); } /*function addEID(address _address, string _commonName, bytes _mod, bytes _exp, bytes _signature, byte _sigAlgo, bytes20 _parentId, bytes _bodyHash) */ function linkEID(address _linked, bytes _crt, bytes _addressSig) external payable onlyInterface checkOracle { // address can only have 1 EID ever // should be secure enough, but could be avoided by initially providing // malformed cert without parentEID, could throw if there's none, or // throw if break is passed if (database_.getParentEID(_linked) != 0 || _linked == address(0)) throw; bytes32 crtHash = sha3(_crt); Certificate memory thisCrt = extractCrt(_crt); database_.addCrt(crtHash, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) : thisCrt.bodyHash, thisCrt.commonName, thisCrt.publicKey.mod, thisCrt.publicKey.exp, thisCrt.signature, thisCrt.sigAlgorithm, thisCrt.parentId, parseSerialFromCN(thisCrt.commonName)); // last argument clears body for SHA-1, to not save 2kb to storage database_.addEID(crtHash, _linked, thisCrt.commonName, _addressSig); //database_.addBodyHash(_linked, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) : thisCrt.bodyHash); oracle_.validateCrt.value(msg.value)(_linked, thisCrt.signature, thisCrt.bodyHash, thisCrt.sigAlgorithm, thisCrt.parentId); } function addCrtWallet(bytes _crt) onlyWalletOracle external { bytes32 crtHash = sha3(_crt); Certificate memory thisCrt = extractCrt(_crt); database_.addCrt(crtHash, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) : thisCrt.bodyHash, thisCrt.commonName, thisCrt.publicKey.mod, thisCrt.publicKey.exp, thisCrt.signature, thisCrt.sigAlgorithm, thisCrt.parentId, parseSerialFromCN(thisCrt.commonName)); /*WalletOracle(msg.sender).processNewCrt(crtHash, _signed, _addressType, _receiverSerial, _receiverAddress, _transferValue, thisCrt.bodyHash, thisCrt.sigAlgorithm);*/ WalletOracle(msg.sender).processNewCrt(crtHash, thisCrt.bodyHash, thisCrt.signature, thisCrt.sigAlgorithm); // last argument clears body for SHA-1, to not save 2kb to storage //database_.addBodyHash(_linked, thisCrt.sigAlgorithm == 0x05 ? new bytes(0) : thisCrt.bodyHash); //oracle_.validateCrt.value(msg.value)(_linked, thisCrt.signature, thisCrt.bodyHash, thisCrt.sigAlgorithm, thisCrt.parentId); } // assumes Serial will always be 11 last characters in the common name function parseSerialFromCN(string _commonName) private constant returns (uint40) { bytes memory converted = bytes(_commonName); uint idIndex = converted.length - 11; bytes memory parsed = new bytes(11); for(uint i = 0; idIndex < converted.length; i++) { parsed[i] = converted[idIndex]; idIndex++; } return uint40(oraclizeLib.parseInt(string(parsed))); } // helpers function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) private returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small assembly { add(minLength, toOffset) to mstore } bytes memory newSized = new bytes(minLength); newSized = to; to = newSized; } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } function extractNameKeyParent(bytes _crt) private returns (bytes commonName, bytes modulus, bytes exponent, bytes20 parentId) { bool skipFirst; uint len; for (uint i=30; i<_crt.length; i++) { if (_crt[i] != 0x30) continue; if (commonName.length == 0) { // check for auth message with i - 3 if (_crt[i+4] == 0x55 && _crt[i+5] == 0x04 && _crt[i+6] == 0x03 && _crt[i+7] == 0x0C) { // skip the first occurrence, which is name of parent cert if (!skipFirst) { skipFirst = true; i += uint(_crt[i+8]) + 8 - 1; //skip this element continue; } len = uint(_crt[i+8]); i += 9; commonName = new bytes(len); commonName = copyBytes(_crt, i, len, commonName, 0); i += len - 1; continue; } } else if (modulus.length == 0) { if (_crt[i+4] == 0x02 && _crt[i+5] == 0x82 && _crt[i+6] == 0x01) { i += 8; while(_crt[i] == 0x00) i++; modulus = new bytes(0x20*8); modulus = copyBytes(_crt, i, 0x20*8, modulus, 0); i += 0x20*8 + 1; // get exponent that follows len = uint(_crt[i++]); exponent = new bytes(len); // mask based on indicated length assembly { let tmp := mload(add(_crt, add(i, 0x20))) let trunc := exp(0x10,sub(0x40, mul(len, 2))) div(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, trunc) trunc mul tmp and add(exponent, 0x20) mstore } continue; } } else { if (_crt[i+1] == 0x16 && _crt[i+2] == 0x80 && _crt[i+3] == 0x14) { i += 4; // parse for bytes20 assembly { let tmp := mload(add(_crt, add(i, 0x20))) and(tmp, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000) =: parentId } break; } } } } function extractSigAlgoHash(bytes _crt) private returns (bytes signature, byte sigAlgorithm, bytes hash) { // extract algo and sig + calc hash for (uint i = 1; i<_crt.length; i++) { if (_crt[i] != 0x30) continue; uint fromIndex = i; uint size = uint(_crt[i+1]) - 0x80; // COULD BE bug //i += size; // replaced with i += 2; uint seqOffset = 2; uint len; while (size > 0) { len = (len * (0x10 ** 2)) + uint(_crt[i++]); size--; seqOffset++; } i += len; sigAlgorithm = _crt[i+12]; hash = getBodyHash(_crt, fromIndex, len, sigAlgorithm, seqOffset); // get sig itself i += 17; len = 0; // search until occurrance of null byte in sig while (_crt[i] != 0x00) { len = (len * (0x10 ** 2)) + uint(_crt[i++]); } // discount null len -= 1; signature = new bytes(len); signature = copyBytes(_crt, _crt.length - len, len, signature, 0); break; } } function getBodyHash(bytes _crt, uint _from, uint _len, byte _algo, uint _offset) private returns (bytes) { // assign sufficient size so sig is ignored // CHANGED was + before but doesn't make sense to me // was _len + _from // coincidentally this was working only because the correct seqOffset // matched with _from bytes memory body = new bytes(_len + _offset); // offset initial sequence body = copyBytes(_crt, _from, body.length, body, 0); if (_algo == 0x0b) { bytes32 tmp = sha256(body); bytes memory hash; assembly { mstore(hash, 0x20) mstore(add(hash, 0x20), tmp) } return hash; } else if (_algo == 0x05) { // return extracted body, so SHA-1 is done off-chain return body; } } function extractCrtOCSP(bytes _crt) external onlyOracles returns (bool ocsp, bytes32 resHash) { for (uint i = 0; i < _crt.length; i++) { if (_crt[i] != 0x30) continue; if (_crt[i+1] != 0x09) continue; // match identifier if (_crt[i+2] == 0x06 && _crt[i+3] == 0x05 && _crt[i+4] == 0x2B && _crt[i+5] == 0x0E && _crt[i+6] == 0x03 && _crt[i+7] == 0x02 && _crt[i+8] == 0x1A) { uint offset = uint(_crt[i-1]); i += offset; if(_crt[i] == 0x80 && _crt[i+1] == 0x00) ocsp = true; uint lenSize = uint(_crt[35]) - 0x80; i = 36; uint seqOffset = 2; uint len; while (lenSize > 0) { len = (len * (0x10 ** 2)) + uint(_crt[i++]); seqOffset++; lenSize--; } // get body hash of response bytes memory body = new bytes(len + seqOffset); // offset initial sequence body = copyBytes(_crt, 34, len, body, 0); resHash = sha256(body); // get sig and pipe it to correct oracle appendSigOCSP(_crt, 34 + len); break; } } } function appendSigOCSP(bytes _crt, uint _offset) private { for (uint i = _offset; i < _crt.length; i++) { if (_crt[i] != 0x30) continue; if (_crt[i+1] != 0x0D) continue; // match identifier if (_crt[i+2] == 0x06 && _crt[i+3] == 0x09 && _crt[i+4] == 0x2A && _crt[i+5] == 0x86 && _crt[i+6] == 0x48 && _crt[i+7] == 0x86 && _crt[i+8] == 0xF7 && _crt[i+9] == 0x0D && _crt[i+10] == 0x01 && _crt[i+11] == 0x01 && _crt[i+12] == 0x0B) { i += 20; bytes memory signature = new bytes(256); signature = copyBytes(_crt, i, 256, signature, 0); // use msg.sender to pipe to correct oracle database_.pipeSigOCSP(signature, msg.sender); break; } } } } contract DigitalIdCostEstimator { uint24[5] public execCost_ = [ 2000000, // sha1 computation 2000000, // rsa cert sig validation 2000000, // rsa addr sig validation (should be same as above) 2000000, // ocsp query 1800000 // rsa ocsp response validation ]; function DigitalIdCostEstimator() { /*oraclizeLib.oraclize_setProof(0x00); oraclizeLib.oraclize_query("URL", "");*/ } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function getOAR() constant returns (address) { return oraclizeLib.getOAR(); } function expectedOracleCosts(bool _sha1) public constant returns (uint) { //uint estimatedQueryCost = getOracleGasCost("URL", queryGasCost); /*uint crtComputationCost = getOracleGasCost("computation", 1800000); uint sha1ComputationCost = _sha1 ? getOracleGasCost("computation", 1500000) : 0; uint ocspQueryCost = getOracleGasCost("nested", 4000000); */ uint totalCost; uint oracleStep = _sha1 ? 0 : 1; // load storage array into memory for efficiency uint24[5] memory costs = execCost_; string memory ds; for (; oracleStep < costs.length; oracleStep++) { ds = oracleStep == 3 ? "nested" : "computation"; totalCost += getOracleGasCost(ds, costs[oracleStep]); } return totalCost; } function expectedOCSPCosts() public constant returns (uint) { uint totalCost; uint24[5] memory costs = execCost_; totalCost += getRequestCost(3); totalCost += getRequestCost(4); return totalCost; } // General helpers function getOracleGasCost(string _type, uint _gasNeeded) public constant returns (uint) { if (_gasNeeded <= 200000) return (oraclizeLib.oraclize_getPrice(_type, 200001) / 200001) * 200000; else return oraclizeLib.oraclize_getPrice(_type, _gasNeeded); } function getRequestCost(uint _action) public constant returns (uint) { string memory ds = _action == 3 ? "nested" : "computation"; return getOracleGasCost(ds, execCost_[_action]); } } contract DigitalIdOracle is usingFixedToDynamicLibrary { // TODO Add suicides to the 2 logics enum cbAction { ComputeHash, ComputeCertSig, ComputeAddrSig, QueryOCSP, ComputeOCSPSig/*, ComputeMsgSig*/ } struct Callback { address sender; cbAction action; bool retry; } struct OCSPRevocation { bool pass; bytes32 hash; } mapping (bytes32 => Callback) private cbTracker_; mapping (address => bytes32) private cbRetry_; //mapping (address => bytes32) private revokingHash_; mapping (bytes32 => OCSPRevocation) private cbRevoking_; //mapping (bytes32 => OCSPRevocation) private //JSON public json_; DigitalIdConnector public connector_; DigitalIdDatabase public database_; DigitalIdLogic public logic_; DigitalIdCostEstimator public coster_; // work-around for sending dynamic types between contracts bytes private pipe_; uint24[5] public execCost_ = [ 2000000, // sha1 computation 2000000, // rsa cert sig validation 2000000, // rsa addr sig validation (should be same as above) 2000000, // ocsp query 1800000 // rsa ocsp response validation ]; modifier onlyLogic() { if (msg.sender != connector_.logic_()) throw; _; } modifier onlyInterface() { if (msg.sender != connector_.interface_()) throw; _; } modifier onlyDatabase() { if (msg.sender != connector_.database_()) throw; _; } function DigitalIdOracle(address _connector) { connector_ = DigitalIdConnector(_connector); // Database must be pre-deployed already database_ = DigitalIdDatabase(connector_.database_()); coster_ = DigitalIdCostEstimator(connector_.coster_()); //oraclize_setProof(proofType_NONE); //oraclize_query('URL', ''); } function validateCrt(address _linked, bytes _signature, bytes _bodyHash, byte _sigAlgo, bytes20 _parentId) external onlyLogic payable { //bytes20 parent = ; //bytes memory parentMod = database_.getHashEID(address(0)); bytes32 callback; cbAction action; if (_sigAlgo == 0x0b) { // sha-256 bytes memory parentExp = hex'010001'; if (database_.pipeParentMod(_parentId)) bytes memory parentMod = pipe_; else throw; action = cbAction.ComputeCertSig; callback = computeRSA(_signature, parentExp, parentMod, execCost_[uint(action)]); } else if(_sigAlgo == 0x05) { //sha-1 callback = computeSHA1(_bodyHash); action = cbAction.ComputeHash; } else { throw; } trackCallback(_linked, action, callback); uint cost = coster_.expectedOracleCosts(cbTracker_[callback].action == cbAction.ComputeHash); if (msg.value < cost) throw; if (!_linked.send(msg.value - cost)) throw; } function trackCallback(address _usr, cbAction _action, bytes32 _cb) private { cbTracker_[_cb] = Callback(_usr, _action, false); } function computeRSA(bytes _base, bytes _exp, bytes _mod, uint _cost) private returns (bytes32 callback) { /*string[3] memory params = [oraclizeLib.b2s(_base), oraclizeLib.b2s(_exp), oraclizeLib.b2s(_mod)]; string[] memory arr; arr[0] = oraclizeLib.b2s(_base); arr[1] = oraclizeLib.b2s(_exp); arr[2] = oraclizeLib.b2s(_mod);*/ //string[] storage arr = ["Qmd3Vdr5AqFCLDqWhx8fcpQKM6FoUMMieR4cGEyNmL44hJ", base, exp, mod]; return oraclizeLib.oraclize_query("computation", ["binary(QmfFdnXLRzhiks7BRbJ3UZmc99WVYXwHissHeJSB1sxHw6).unhexlify()", oraclizeLib.b2s(_base), oraclizeLib.b2s(_exp), oraclizeLib.b2s(_mod)].toDynamic(), _cost); } function computeSHA1(bytes _body) private returns (bytes32 callback) { return oraclizeLib.oraclize_query("computation", ["binary(QmeTKU7RYZ4NpxHPKAP4oa6znp7hre1SozBtGa9qvD1L7w).unhexlify()", oraclizeLib.b2s(_body)].toDynamic(), execCost_[0]); } function requestPostOCSPCheck(address _user, address _requester) external onlyInterface payable { uint cost = coster_.expectedOCSPCosts(); if (msg.value < cost) throw; if (database_.pipeCommonNameEID(_user)) string memory cn = string(pipe_); else throw; trackCallback(_user, cbAction.QueryOCSP, queryOCSP(cn)); if (!_requester.send(msg.value - cost)) throw; } function queryOCSP(string _cn) private returns (bytes32 callback) { return oraclizeLib.oraclize_query("nested", oraclizeLib.strConcat("[URL] http://esteid.oraclize.it/ocsp/_sign?otype=cert&key=${[decrypt] BG+04c4ksqrXd+YyV/AtAXkpfg017wRxBkxcxtKtVHml9VXuEo++koFXVWqKfiAo7TU2KamWspeCzsMSRddOggszdWaSJ5bQUrxw6tBZ9JdfDuvLQiEjJX8EOGd7BGw2LTD04Umk4zU1Fc2iyQzAx2G9ztZXrkF8+1EYoyvDTvlIGT2/PT5lgWWjauYs5iwtrg==}&cn=", _cn), execCost_[3]); } function verifySigOCSP(bytes _sig) private returns (bytes32 callback) { bytes memory ocspResponderMod = hex'8a1bc6ca1315ae045e1e5b8a967d736ba82f084fe69524449968c91692fd965bee1146683c5232a5803c839bb555f824796e600eadb98c03aae05c977831886bea499f6874a3659cd9a7a9a551bf7a67c69bf8c0f238dec8caf01fc7c026ba9543b73d5f6c52c0911c87f3f677c09f319b79605ea0a8bb4fbc6d5bfa7ea8b41640e708c815f27f8a7241314bea1d2cf7f8f2dfc4edbf4f75b293f73c33d1c832a4de96aca230646059e8625353ac2fd6ab9afddd42b1ecd709babc76b17e97d607d6001697a8f5a62a84f0b156dff3a3635007abf1c994b486c3ab5cbed2c514e83896aab27be56dfd1eacf3c5b511d4bdba23618825f9fce5cf426de9026837'; return computeRSA(_sig, hex'010001', ocspResponderMod, execCost_[uint(cbAction.ComputeOCSPSig)]); } function sendPipe(bytes _pipe) external onlyDatabase { pipe_ = _pipe; } // adds retry flag, allowing query to be re-attempted in case of service failure function failedCallback(bytes32 _cb, address _sender) private { cbTracker_[_cb].retry = true; cbRetry_[_sender] = _cb; } function retryCallback(address _linked) external onlyInterface payable { bytes32 cb = cbRetry_[_linked]; if (cb == 0) throw; Callback memory cbObj = cbTracker_[cb]; uint cost = coster_.getRequestCost(uint(cbObj.action)); // ensure sufficient amount was paid to pay for redoing the Callback // IMPORTANT / DANGER check here for potential refund exploits if (msg.value < cost) throw; requestOracleQuery(cb, cbObj, true); delete cbRetry_[_linked]; // IMPORTANT / DANGER check here for potential refund exploits if(!_linked.send(msg.value - cost)) throw; } function requestOracleQuery(bytes32 _cb, Callback _cbObj, bool _isRetry) private { requestOracleQuery(_cb, _cbObj, _isRetry, OCSPRevocation(false, 0)); } function requestOracleQuery(bytes32 _cb, Callback _cbObj, bool _isRetry, OCSPRevocation _ocsp) private { uint nextAction = uint(_cbObj.action); nextAction = _isRetry ? nextAction : nextAction + 1; bytes memory sig; if (nextAction == uint(cbAction.ComputeCertSig)) { if (database_.pipeCrtSigEID(_cbObj.sender)) sig = pipe_; else throw; if (database_.pipeParentMod(database_.getParentEID(_cbObj.sender))) bytes memory parentMod = pipe_; else throw; trackCallback(_cbObj.sender, cbAction.ComputeCertSig, computeRSA(sig, hex'010001', parentMod, execCost_[nextAction])); } else if (nextAction == uint(cbAction.ComputeAddrSig)) { if (database_.pipeUsrSigEID(_cbObj.sender)) sig = pipe_; else throw; if (database_.pipeUsrModEID(_cbObj.sender)) bytes memory mod = pipe_; else throw; if (database_.pipeUsrExpEID(_cbObj.sender)) bytes memory exp = pipe_; else throw; trackCallback(_cbObj.sender, cbAction.ComputeAddrSig, computeRSA(sig, exp, mod, execCost_[nextAction])); } else if (nextAction == uint(cbAction.QueryOCSP)) { if (database_.pipeCommonNameEID(_cbObj.sender)) string memory cn = string(pipe_); else throw; trackCallback(_cbObj.sender, cbAction.QueryOCSP, queryOCSP(cn)); } else if (nextAction == uint(cbAction.ComputeOCSPSig)) { // extracted sig already in pipe sig = pipe_; bytes32 cb = verifySigOCSP(sig); //if (_ocsp.hash != 0) cbRevoking_[cb] = _ocsp; trackCallback(_cbObj.sender, cbAction.ComputeOCSPSig, cb); } // get storage refund delete cbTracker_[_cb].sender; delete cbTracker_[_cb].action; if (_isRetry) delete cbTracker_[_cb].retry; } function __callback(bytes32 _cb, string _result) { if (msg.sender!= oraclizeLib.oraclize_cbAddress()) throw; Callback memory cbObj = cbTracker_[_cb]; if(sha3(_result) == sha3("") || bytes(_result).length == 0) { failedCallback(_cb, cbObj.sender); database_.emitLinkEvent(cbObj.sender, 0, 0x02); return; } // if retrieved hash is empty, result must be sha1 if (cbObj.action == cbAction.ComputeHash) { bytes memory sha1 = bytes(_result); if (sha1.length == 20) { database_.appendSHA1BodyHash(cbObj.sender, sha1); } else { database_.emitLinkEvent(cbObj.sender, 1, 0x03); return; } // SHA-1 computed and added, begin cert RSA validation requestOracleQuery(_cb, cbObj, false); database_.emitLinkEvent(cbObj.sender, 1, 0x01); return; } // runs for initial OCSP callback if (cbObj.action == cbAction.QueryOCSP) { bool ocspPass; bytes32 ocspHash; if (logic_ != connector_.logic_()) { logic_ = DigitalIdLogic(connector_.logic_()); } // sends extracted sig to pipe, for later use in requestOracleQuery (ocspPass, ocspHash) = logic_.extractCrtOCSP(bytes(_result)); //bytes memory ocspSig = pipe_; // check if user's cert passed ocsp /*if (!ocspPass) revoking_[cbObj.sender] = true; else if(revoking_[cbObj.sender] == true) delete revoking_[cbObj.sender]; */ //database_.appendOCSPHash(cbObj.sender, ocspHash); requestOracleQuery(_cb, cbObj, false, OCSPRevocation(ocspPass, ocspHash)); return; } bytes memory result = bytes(_result); bytes memory hash; // throw here so Oraclize is discouraged from providing false results // TODO: To be decided, potentially useless as funds will be in this contract anyways // also ends up not providing feedback to user /*if (result[0] != 0x01) throw; */ if (cbObj.action == cbAction.ComputeCertSig) { if (database_.pipeHashEID(cbObj.sender)) hash = pipe_; else return; //potentially add retry here? although it shouldn't occur, and if it does, it's not retryable anyways bytes memory resultHash = new bytes(hash.length); resultHash = copyBytes(result, result.length - hash.length, hash.length, resultHash, 0); if (sha3(hash) == sha3(resultHash)) { database_.setValidityEID(cbObj.sender, 2); // initiate address signature validation requestOracleQuery(_cb, cbObj, false); database_.emitLinkEvent(cbObj.sender, 2, 0x01); return; // do ocsp } else { database_.emitLinkEvent(cbObj.sender, 2, 0x03); return; } } else if (cbObj.action == cbAction.ComputeAddrSig) { bytes memory addressHash = new bytes(32); addressHash = copyBytes(result, result.length - 32, 32, addressHash, 0); if (sha3(sha256(cbObj.sender)) == sha3(addressHash)) { database_.setValidityEID(cbObj.sender, 3); // initiate OCSP revocation check requestOracleQuery(_cb, cbObj, false); database_.emitLinkEvent(cbObj.sender, 3, 0x01); return; } else { database_.emitLinkEvent(cbObj.sender, 3, 0x03); return; } } else if (cbObj.action == cbAction.ComputeOCSPSig) { OCSPRevocation memory ocsp = cbRevoking_[_cb]; bytes memory resultOCSPHash = new bytes(32); resultOCSPHash = copyBytes(result, result.length - 32, 32, resultOCSPHash, 0); if (sha3(ocsp.hash) == sha3(resultOCSPHash)) { if (ocsp.pass == false) { // could be revoked wantonly with a malicious certificate, should track callback too // not any longer, revocation is tied to specific cert used, not last database_.ocspUpdateEID(cbObj.sender, true); database_.emitLinkEvent(cbObj.sender, 4, 0x04); return; } else { // EID fully validated database_.ocspUpdateEID(cbObj.sender, false); database_.setValidityEID(cbObj.sender, 4); database_.emitLinkEvent(cbObj.sender, 4, 0x01); return; } } else { database_.emitLinkEvent(cbObj.sender, 4, 0x03); return; } } } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) private returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small assembly { add(minLength, toOffset) to mstore } bytes memory newSized = new bytes(minLength); newSized = to; to = newSized; } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } } contract WalletOracle is usingFixedToDynamicLibrary { // to receive oracle funding during testing function () payable { } enum cbAction { ComputeHash, ComputeCertSig, QueryOCSP, ComputeOCSPSig, ComputeSigning } enum pipeId { nil, commonName, mod, exp, crtSignature, bodyHash, parentMod } struct Callback { bytes32 crtId; cbAction action; bytes32 transferId; } struct OCSPRevocation { bool pass; bytes32 hash; } struct Transfer { bytes signature; address token; bool executed; bool transferred; bool addressType; // true if type of receiver is address, false if eid uint40 senderSerial; uint40 receiverSerial; address receiverAddress; uint value; string message; uint nonce; } /*struct TempTransfer { bytes signed; address token; bool addressType; uint40 receiverSerial; address receiverAddress; uint value; string message; uint nonce; }*/ Transfer private tempTransfer_; mapping (bytes32 => Transfer) private transfer_; mapping (bytes32 => Callback) private cbTracker_; //mapping (address => bytes32) private revokingHash_; mapping (bytes32 => OCSPRevocation) private cbRevoking_; //mapping (bytes32 => OCSPRevocation) private //JSON public json_; DigitalIdConnector public connector_; DigitalIdDatabase public database_; WalletContainer public walletContainer_; // work-around for sending dynamic types between contracts bytes private pipe_; /* uint24[5] public execCost_ = [ 2000000, // sha1 computation 1000000, // rsa cert sig validation 1100000, 1800000, 1000000 // rsa msg sig validation (should be same as above) ];*/ function WalletOracle(address _connector, address _wallet) { connector_ = DigitalIdConnector(_connector); // Database must be pre-deployed already database_ = DigitalIdDatabase(connector_.database_()); walletContainer_ = WalletContainer(_wallet); // oraclize_setProof(proofType_NONE); } function processNewCrt(bytes32 _crtId, bytes _bodyHash, bytes _crtSig, byte _sigAlgo) external { if (msg.sender != connector_.logic_()) throw; //bytes20 parent = ; Transfer memory trf = tempTransfer_; uint40 senderSerial = database_.getSerialCrt(_crtId); bytes32 transferId = sha3(_crtId, trf.signature, trf.addressType, senderSerial, trf.receiverSerial, trf.receiverAddress, trf.value, trf.message, trf.nonce); // transfer struct with exec and transf bools omitted transfer_[transferId] = Transfer(trf.signature, trf.token, false, false, trf.addressType, senderSerial, trf.receiverSerial, trf.receiverAddress, trf.value, trf.message, trf.nonce); //bytes memory parentMod = database_.getHashEID(address(0)); bytes32 callback; cbAction action; oraclizeLib.useCoupon('free'); if (_sigAlgo == 0x0b) { // sha-256 bytes memory parentExp = hex'010001'; if (!database_.pipeToWalletOracle(_crtId, uint(pipeId.parentMod))) throw; bytes memory parentMod = pipe_; action = cbAction.ComputeCertSig; callback = idOracleLib.computeRSA(_crtSig, parentExp, parentMod, 2000000); } else if(_sigAlgo == 0x05) { //sha-1 callback = idOracleLib.computeSHA1(_bodyHash); action = cbAction.ComputeHash; } else { throw; } Callback memory cbObj = Callback(_crtId, action, transferId); trackCallback(cbObj, action, callback); // get refund from temp var delete tempTransfer_; //return transferId; } function extractNewCrtThenVerifySig(bytes _crt, bytes _signed, address _token, bool _addressType, uint40 _receiverSerial, address _receiverAddress, uint _transferValue, string _message, uint _nonce) external { if (msg.sender != address(walletContainer_)) throw; // save to storage for later re-use tempTransfer_ = Transfer(_signed, _token, false, false, _addressType, 0, _receiverSerial, _receiverAddress, _transferValue, _message, _nonce); // addCrtWallet will be routed to addNewCrt locally DigitalIdLogic(connector_.logic_()).addCrtWallet(_crt); } function requestSigVerify(bytes32 _crtId, bytes _signed, address _token, bool _addressType, uint40 _senderSerial, uint40 _receiverSerial, address _receiverAddress, uint _transferValue, string _message, uint _nonce) external { if (msg.sender != address(walletContainer_)) throw; requestSigVerify(_crtId, Transfer(_signed, _token, false, false, _addressType, _senderSerial, _receiverSerial, _receiverAddress, _transferValue, _message, _nonce)); } // ~400k deployment gas :( function requestSigVerify(bytes32 _crtId, Transfer _trf) private { bytes32 transferId = sha3(_crtId, _trf.signature, _trf.token, _trf.addressType, _trf.senderSerial, _trf.receiverSerial, _trf.receiverAddress, _trf.value, _trf.message, _trf.nonce); transfer_[transferId] = _trf; // stays in effect, there should be some reset oraclizeLib.useCoupon('free'); // pipe vars needed from database if (!database_.pipeToWalletOracle(_crtId, uint(pipeId.mod))) throw; bytes memory mod = pipe_; if (!database_.pipeToWalletOracle(_crtId, uint(pipeId.exp))) throw; bytes memory exp = pipe_; bytes32 cbRSA = idOracleLib.computeRSA(_trf.signature, exp, mod, 2500000); Callback memory cbObj = Callback(_crtId, cbAction.ComputeSigning, transferId); trackCallback(cbObj, cbAction.ComputeSigning, cbRSA); } function trackCallback(Callback _prevCbObj, cbAction _action, bytes32 _cb) private { cbTracker_[_cb] = Callback(_prevCbObj.crtId, _action, _prevCbObj.transferId); } function sendPipe(bytes _pipe) external { if (msg.sender != address(database_)) throw; pipe_ = _pipe; } function requestOracleQuery(Callback _cbObj) private { requestOracleQuery(_cbObj, OCSPRevocation(false, 0)); } function requestOracleQuery(Callback _cbObj, OCSPRevocation _ocsp) private { uint nextAction = uint(_cbObj.action); nextAction = nextAction + 1; bytes memory sig; if (nextAction == uint(cbAction.ComputeCertSig)) { if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.crtSignature))) throw; sig = pipe_; if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.parentMod))) throw; bytes memory parentMod = pipe_; trackCallback(_cbObj, cbAction.ComputeCertSig, idOracleLib.computeRSA(sig, hex'010001', parentMod, 1000000)); } else if (nextAction == uint(cbAction.QueryOCSP)) { if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.commonName))) throw; string memory cn = string(pipe_); trackCallback(_cbObj, cbAction.QueryOCSP, idOracleLib.queryOCSP(cn)); } else if (nextAction == uint(cbAction.ComputeOCSPSig)) { // verify the provided signature with known valid ocsp cert // extracted sig already in pipe sig = pipe_; bytes32 cb = idOracleLib.verifySigOCSP(sig); //if (_ocsp.hash != 0) cbRevoking_[cb] = _ocsp; trackCallback(_cbObj, cbAction.ComputeOCSPSig, cb); } else if (nextAction == uint(cbAction.ComputeSigning)) { // should do address to hash translation // needs to be handled somehow :/, accessing wallet? sig = transfer_[_cbObj.transferId].signature; if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.mod))) throw; bytes memory mod = pipe_; if (!database_.pipeToWalletOracle(_cbObj.crtId, uint(pipeId.exp))) throw; bytes memory exp = pipe_; trackCallback(_cbObj, cbAction.ComputeSigning, idOracleLib.computeRSA(sig, exp, mod, 1000000)); } // get storage refund /*delete cbTracker_[_cb].crtId; delete cbTracker_[_cb].action;*/ } function __callback(bytes32 _cb, string _result) { if (msg.sender != oraclizeLib.oraclize_cbAddress()) throw; Callback memory cbObj = cbTracker_[_cb]; if(sha3(_result) == sha3("") || bytes(_result).length == 0) { //failedCallback(_cb, cbObj.crtId); database_.emitValidatingEvent(cbObj.crtId, 0, 0x02); return; } // if retrieved hash is empty, result must be sha1 if (cbObj.action == cbAction.ComputeHash) { bytes memory sha1 = bytes(_result); if (sha1.length == 20) { database_.appendSHA1BodyHash(cbObj.crtId, sha1); } else { database_.emitValidatingEvent(cbObj.crtId, 1, 0x03); return; } // SHA-1 computed and added, begin cert RSA validation requestOracleQuery(cbObj); database_.emitValidatingEvent(cbObj.crtId, 1, 0x01); return; } // runs for initial OCSP callback if (cbObj.action == cbAction.QueryOCSP) { bool ocspPass; bytes32 ocspHash; DigitalIdLogic logic = DigitalIdLogic(connector_.logic_()); // sends extracted sig to pipe, for later use in requestOracleQuery (ocspPass, ocspHash) = logic.extractCrtOCSP(bytes(_result)); //bytes memory ocspSig = pipe_; // check if user's cert passed ocsp //database_.appendOCSPHash(cbObj.sender, ocspHash); requestOracleQuery(cbObj, OCSPRevocation(ocspPass, ocspHash)); return; } bytes memory result = bytes(_result); // throw here so Oraclize is discouraged from providing false results // TODO: To be decided, potentially useless as funds will be in this contract anyways // also ends up not providing feedback to user if (cbObj.action == cbAction.ComputeCertSig) { bytes memory expectHash; if (!database_.pipeToWalletOracle(cbObj.crtId, uint(pipeId.bodyHash))) throw; expectHash = pipe_; // expectHash length is dependent upon sigAlgo, hence just base it off the state's expectHash bytes memory resultHash = new bytes(expectHash.length); resultHash = copyBytes(result, result.length - expectHash.length, expectHash.length, resultHash, 0); if (sha3(expectHash) == sha3(resultHash)) { database_.setCrtValidated(cbObj.crtId); // initiate address signature validation requestOracleQuery(cbObj); database_.emitValidatingEvent(cbObj.crtId, 2, 0x01); return; } else { database_.emitValidatingEvent(cbObj.crtId, 2, 0x03); return; } } else if (cbObj.action == cbAction.ComputeOCSPSig) { OCSPRevocation memory ocsp = cbRevoking_[_cb]; bytes memory resultOCSPHash = new bytes(32); resultOCSPHash = copyBytes(result, result.length - 32, 32, resultOCSPHash, 0); if (sha3(ocsp.hash) == sha3(resultOCSPHash)) { if (ocsp.pass == false) { // could be revoked wantonly with a malicious certificate, should track callback too // not any longer, revocation is tied to specific cert used, not last database_.ocspUpdateCrt(cbObj.crtId, true); database_.emitValidatingEvent(cbObj.crtId, 3, 0x04); return; } else { // Crt passed OCSP check database_.ocspUpdateCrt(cbObj.crtId, false); requestOracleQuery(cbObj); database_.emitValidatingEvent(cbObj.crtId, 3, 0x01); return; } } else { database_.emitValidatingEvent(cbObj.crtId, 3, 0x03); return; } } else if (cbObj.action == cbAction.ComputeSigning) { // should likely be last step, after ocsp checks complete bytes memory signedHash = new bytes(32); signedHash = copyBytes(result, result.length - 32, 32, signedHash, 0); Transfer memory tfr = transfer_[cbObj.transferId]; if (sha3( tfr.addressType ? sha256(tfr.receiverAddress, tfr.token, tfr.value, tfr.message, tfr.nonce) : sha256(tfr.receiverSerial, tfr.token, tfr.value, tfr.message, tfr.nonce) ) == sha3(signedHash) ) { // call wallet here and execute transfer; // ensure nonce is current if (database_.incrementCrtTxNonce(cbObj.crtId, tfr.nonce)) { walletContainer_.executeDelegatedTransfer(tfr.senderSerial, tfr.addressType, tfr.receiverSerial, tfr.receiverAddress, tfr.token, tfr.value, tfr.message); database_.emitValidatingEvent(cbObj.crtId, 4, 0x01); } else { database_.emitValidatingEvent(cbObj.crtId, 4, 0x04); } return; } else { database_.emitValidatingEvent(cbObj.crtId, 4, 0x03); return; } } } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) private returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small assembly { add(minLength, toOffset) to mstore } bytes memory newSized = new bytes(minLength); newSized = to; to = newSized; } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } } // math.sol -- mixin for inline numerical wizardry // Copyright (C) 2015, 2016, 2017 DappHub, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). contract DSMath { function assert(bool assertion) internal { if (!assertion) throw; } /* standard uint256 functions */ function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x * y) >= x); } function div(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) constant internal returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions (h is for half) */ function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x + y) >= x); } function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x - y) <= x); } function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x * y) >= x); } function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = x / y; } function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { return x <= y ? x : y; } function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { return x >= y ? x : y; } /* int256 functions */ function imin(int256 x, int256 y) constant internal returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) constant internal returns (int256 z) { return x >= y ? x : y; } /* WAD math */ uint128 constant WAD = 10 ** 18; function wadd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function wmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } /* RAY math */ uint128 constant RAY = 10 ** 27; function radd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function rsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + RAY / 2) / RAY); } function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * RAY + y / 2) / y); } function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) { // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } function rmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function rmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } function cast(uint256 x) constant internal returns (uint128 z) { assert((z = uint128(x)) == x); } } contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint public decimals; string public name; } // handle ocsp revocation on poi-side contract WalletContainer is DSMath { struct Balance { uint eth; mapping(address => uint) token; } struct Transfer { bytes signed; address token; bool addressType; uint40 receiverSerial; address receiverAddress; uint value; string message; uint nonce; } Transfer transfer_; mapping(uint40 => Balance) public balances_; event LOG_receivedTransfer(uint40 indexed receiverSerial, uint40 senderSerial, address senderAddress, address indexed token, uint amount, string note, uint time); event LOG_sentTransfer(uint40 indexed senderSerial, uint40 receiverSerial, address receiverAddress, address indexed token, uint amount, string note, uint time); event LOG_balanceUpdate(uint40 indexed serial, address indexed token, uint amount, uint time); DigitalIdConnector public connector_; DigitalIdDatabase public database_; WalletOracle public walletOracle_; uint public birthBlock_; modifier checkWalletOracle() { if (walletOracle_ != connector_.walletOracle_()) { walletOracle_ = WalletOracle(connector_.walletOracle_()); } _; } // assumes all EID serials are and will be 11 digits modifier serialCheck(uint40 _serial) { if (_serial > 99999999999 || _serial < 10000000000) throw; _; } // connect to oracle here and db function WalletContainer(address _connector) { connector_ = DigitalIdConnector(_connector); database_ = DigitalIdDatabase(connector_.database_()); birthBlock_ = block.number; } function getBalance(uint40 _serial) public constant returns (uint) { return getBalance(_serial, 0); } function getBalance(uint40 _serial, address _token) public constant returns (uint) { if (_token == 0) return balances_[_serial].eth; else return balances_[_serial].token[_token]; } function sendEtherToEID(uint40 _serial) payable external returns (bool success) { success = sendEtherToEID(_serial, ''); } function sendEtherToEID(uint40 _serial, string _msg) payable serialCheck(_serial) public returns (bool success) { balances_[_serial].eth = add(msg.value, balances_[_serial].eth); LOG_receivedTransfer(_serial, 0, msg.sender, 0, msg.value, _msg, now); success = true; LOG_balanceUpdate(_serial, 0, balances_[_serial].eth, now); } function sendTokensToEID(uint40 _serial, address _token, uint _amount) external returns (bool success) { // may be reserved for ether down the line? success = sendTokensToEID(_serial, _token, _amount, ''); //balances_[_serial] = add() } function sendTokensToEID(uint40 _serial, address _token, uint _amount, string _msg) serialCheck(_serial) public returns (bool success) { // may be reserved for ether down the line? if (_token == 0) throw; if (!Token(_token).transferFrom(msg.sender, this, _amount)) throw; balances_[_serial].token[_token] = add(_amount, balances_[_serial].token[_token]); LOG_receivedTransfer(_serial, 0, msg.sender, _token, _amount, _msg, now); success = true; LOG_balanceUpdate(_serial, _token, balances_[_serial].token[_token], now); } function transferEtherToAddress(bytes _crt, bytes _signed, address _signedReceiverAddress, uint _signedValue, string _signedMessage, uint _signedNonce) external { Transfer memory trf = Transfer(_signed, 0, true, 0, _signedReceiverAddress, _signedValue, _signedMessage, _signedNonce); requestTransferToOracle(_crt, trf); } function transferTokenToAddress(bytes _crt, bytes _signed, address _signedToken, address _signedReceiverAddress, uint _signedValue, string _signedMessage, uint _signedNonce) external { Transfer memory trf = Transfer(_signed, _signedToken, true, 0, _signedReceiverAddress, _signedValue, _signedMessage, _signedNonce); requestTransferToOracle(_crt, trf); } function transferEtherToSerial(bytes _crt, bytes _signed, uint40 _signedReceiverSerial, uint _signedValue, string _signedMessage, uint _signedNonce) serialCheck(_signedReceiverSerial) external { Transfer memory trf = Transfer(_signed, 0, false, _signedReceiverSerial, 0, _signedValue, _signedMessage, _signedNonce); requestTransferToOracle(_crt, trf); } function transferTokenToSerial(bytes _crt, bytes _signed, address _signedToken, uint40 _signedReceiverSerial, uint _signedValue, string _signedMessage, uint _signedNonce) serialCheck(_signedReceiverSerial) external { Transfer memory trf = Transfer(_signed, _signedToken, false, _signedReceiverSerial, 0, _signedValue, _signedMessage, _signedNonce); requestTransferToOracle(_crt, trf); } function requestTransferToOracle(bytes _crt, Transfer _trf) private { // send cert and sig to be verified // check if crt is already in database bytes32 crtId = sha3(_crt); // maybe check at end post-increment?! // CURRENTLY ALLOWS ONLY FOR ONE TX AT A TIME AND NOT QEUEING SEVERAL if (database_.getCrtTxNonce(crtId) != _trf.nonce) throw; bool valid; bool revoked; uint ocspLastTimestamp; uint ocspLastBlock; (valid, revoked, ocspLastTimestamp, ocspLastBlock) = database_.getCrtStatus(crtId); if(revoked) { //DEBUG don't throw if revoked //throw; onlyTrfSigValidation(_crt, crtId, _trf); } else if(valid && ocspLastTimestamp > 0) { onlyTrfSigValidation(_crt, crtId, _trf); } else { fullCrtValidation(_crt, _trf); } } function onlyTrfSigValidation(bytes _crt, bytes32 _crtId, Transfer _trf) checkWalletOracle private { // check here if there's even sufficient balance, so not to waste computing resources if (!sufficientBalance(database_.getSerialCrt(_crtId), _trf.token, _trf.value)) throw; // TODO // periodic ocsp check or ocsp check above certain amounts!? walletOracle_.requestSigVerify(_crtId, _trf.signed, _trf.token, _trf.addressType, database_.getSerialCrt(_crtId), _trf.receiverSerial, _trf.receiverAddress, _trf.value, _trf.message, _trf.nonce); } function fullCrtValidation(bytes _crt, Transfer _trf) checkWalletOracle private { // schedule for trf sig validation walletOracle_.extractNewCrtThenVerifySig(_crt, _trf.signed, _trf.token, _trf.addressType, _trf.receiverSerial, _trf.receiverAddress, _trf.value, _trf.message, _trf.nonce); } function sufficientBalance(uint40 _serial, address _token, uint _value) private constant returns (bool) { if (_token == 0) return balances_[_serial].eth >= _value; else return balances_[_serial].token[_token] >= _value; } function executeDelegatedTransfer(uint40 _senderSerial, bool _addressType, uint40 _receiverSerial, address _receiverAddress, address _token, uint _value, string _msg) external returns (bool transferred) { // only allow current walletOracle to execute the transfer if(msg.sender != connector_.walletOracle_()) throw; if(_addressType) { if(_token == 0) { return executeAddressTransferETH(_senderSerial, _receiverAddress, _value, _msg); } else { return executeAddressTransferToken(_senderSerial, _receiverAddress, _token, _value, _msg); } } else { if(_token == 0) { return executeSerialTransferETH(_senderSerial, _receiverSerial, _value, _msg); } else { return executeSerialTransferToken(_senderSerial, _receiverSerial, _token, _value, _msg); } } } function executeAddressTransferETH(uint40 _senderSerial, address _receiverAddress, uint _value, string _msg) private returns (bool transferred) { if (balances_[_senderSerial].eth >= _value) { // underflow check balances_[_senderSerial].eth = sub(balances_[_senderSerial].eth, _value); if(!_receiverAddress.send(_value)) { return false; } // emit event here LOG_sentTransfer(_senderSerial, 0, _receiverAddress, 0, _value, _msg, now); LOG_balanceUpdate(_senderSerial, 0, balances_[_senderSerial].eth, now); return true; } else { // emit event here return false; } } function executeAddressTransferToken(uint40 _senderSerial, address _receiverAddress, address _token, uint _value, string _msg) private returns (bool transferred) { if (balances_[_senderSerial].token[_token] >= _value) { // underflow check balances_[_senderSerial].token[_token] = sub(balances_[_senderSerial].token[_token], _value); if(!Token(_token).transfer(_receiverAddress, _value)) { return false; } // emit event here LOG_sentTransfer(_senderSerial, 0, _receiverAddress, _token, _value, _msg, now); LOG_balanceUpdate(_senderSerial, _token, balances_[_senderSerial].token[_token], now); return true; } else { // emit event here return false; } } function getHashForTransfer(uint40 _serialReceiver, address _token, uint _value, string _msg, uint _nonce) public constant returns (bytes32 hash) { // address 0 is considered ether tokens hash = sha256(_serialReceiver, _token, _value, _msg, _nonce); } function getHashForTransfer(address _addressReceiver, address _token, uint _value, string _msg, uint _nonce) public constant returns (bytes32 hash) { hash = sha256(_addressReceiver, _token, _value, _msg, _nonce); } function executeSerialTransferETH(uint40 _senderSerial, uint40 _receiverSerial, uint _value, string _msg) private returns (bool transferred) { if (balances_[_senderSerial].eth >= _value) { balances_[_senderSerial].eth = sub(balances_[_senderSerial].eth, _value); // add underflow/overflow checks balances_[_receiverSerial].eth = add(balances_[_receiverSerial].eth, _value); // emit event here LOG_sentTransfer(_senderSerial, _receiverSerial, 0, 0, _value, _msg, now); LOG_balanceUpdate(_senderSerial, 0, balances_[_senderSerial].eth, now); LOG_receivedTransfer(_receiverSerial, _senderSerial, 0, 0, _value, _msg, now); LOG_balanceUpdate(_receiverSerial, 0, balances_[_receiverSerial].eth, now); return true; } else { // emit event here return false; } } function executeSerialTransferToken(uint40 _senderSerial, uint40 _receiverSerial, address _token, uint _value, string _msg) private returns (bool transferred) { if (balances_[_senderSerial].token[_token] >= _value) { // remove balance from sender balances_[_senderSerial].token[_token] = sub(balances_[_senderSerial].token[_token], _value); // add balance towards receiver balances_[_receiverSerial].token[_token] = add(balances_[_receiverSerial].token[_token], _value); // emit event here LOG_sentTransfer(_senderSerial, _receiverSerial, 0, _token, _value, _msg, now); LOG_balanceUpdate(_senderSerial, _token, balances_[_senderSerial].token[_token], now); LOG_receivedTransfer(_receiverSerial, _senderSerial, 0, _token, _value, _msg, now); LOG_balanceUpdate(_receiverSerial, _token, balances_[_receiverSerial].token[_token], now); return true; } else { // emit event here return false; } } }
add these manually after the fact as owner using ones needed as specified by https:www.sk.ee/en/repository/certs/ ESTEID-SK 2011 ESTEID-SK 2015
function whiteListParents() private { parentCrts_[0x7B6AF255505CB8D97A088741AEFAA22B3D5B5776] = hex'b3e97c6c661eabfda5dc35ede44a934c3aa990a005d4a73cdcaf8652686661ffb247222a65bcd8bab5b5bf94aeec02246c6fae4accc5913846ae95deba8206c33e06ba914f7b0be0171aeefe0d1397b2d8d43afe9596b1d95409cb9883a4c9ca566b18ccf847d03d9b83c446e4c3de81dff7c6ebd65ba77b3dcba58487053963d222425f184e41a7354c627506ce375046426f87544b204dfdb627aafa1b716c134eeb9cc36c90d0b70e3b8b48250a178907d2b54654af4176209d15a6631c4ca48f08c81b3aa7cb1c9129ee186c9e81f40066f797921603011ed644614faad15508406840180bab3935e35a2d53b2c038da69cb190644239197317b5a6e9e75'; parentCrts_[0xB3AB88BC99D562A4852A08CDB41D723B83724751] = hex'd281fad4d0f16dd5bd93c9cb035a8668be01eefc9da1dd84c29fd24c1641df012d20908b764a44b12f295df16246ac0356c80619bbbe43df6dae56f92c8ef28bbac8911a2fe4d7ed05d48d3d2539ac08583d086f6594203b045a1dae44cbe05a2c91e62ea6104bd850bd0b02632c2cfb156f3455292b4a460fae22c9ca9d32e065fe75aaddf2ee669a70061d15165b66e2786bff54b447d4d1269a855066c6af838afc3c1e6d0e4f8e1752e3480250dc260bb7cf438bc81fec7e4c2936686faedcca00cf422ba555aa8b0cc6fefc6b7ae3cf02481778509e61fe9f5cbb06cf85a2bec6456e9876a4c8c42eeeac96d9415df006ddf1afe37b7dd555e2732cd1fde4f976c07ecc5b16d6c1d5fb538d3ebfaace00f1087d9c9aeaa864d7c822af9bba86f7780f1e7be5e924a250afed6a1ab9a18208ef02173b9ba714e31fd07f1c1162121536125ffac2954e191085b27d5f1b8a937735f30ca6c0bd66a430f43c8189aa5b2c31e8ae2782336a015b80448634351de22726d21413f029907949b519b59e058b1ea8f84c417f7b40504b5c92d5cb6482ca8033ec1ab5a80e37fbe11c89b37ec817359d0b36668abc724f4c2b46c2c4331e524414cfa55e406a7af4898e42bb30e3aa93cf49ad750acc49b9e45c2b8b6a7e5d3e6dbce09f4799aaa2622ea3e8a2dc6763645270d015eb015653049be7c76b6891ea59c0158674e941'; }
5,533,982
// SPDX-License-Identifier: MIT /** ∩~~~~∩ ξ ・×・ ξ ξ ~ ξ ξ   ξ ξ   “~~~~〇 ξ       ξ ξ ξ ξ~~~ξ ξ ξ   ξ_ξξ_ξ ξ_ξξ_ξ Alpaca Fin Corporation */ pragma solidity 0.6.6; import "@pancakeswap-libs/pancake-swap-core/contracts/interfaces/IPancakePair.sol"; import "../apis/pancake/IPancakeRouter02.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IWorker02.sol"; import "../interfaces/IPancakeMasterChef.sol"; import "../../utils/AlpacaMath.sol"; import "../../utils/SafeToken.sol"; /// @notice Simplified version of worker for testing purpose. contract MockPancakeswapV2CakeMaxiWorker is IWorker02 { using SafeToken for address; address public override baseToken; address public override farmingToken; address[] public path; address[] public rewardPath; constructor( address _baseToken, address _farmingToken, address[] memory _path, address[] memory _rewardPath) public { baseToken = _baseToken; farmingToken = _farmingToken; path = _path; rewardPath = _rewardPath; } /// @dev Work on the given position. Must be called by the operator. /// @param user The original user that is interacting with the operator. /// @param debt The amount of user debt to help the strategy make decisions. /// @param data The encoded data, consisting of strategy address and calldata. function work(uint256 /* id */, address user, uint256 debt, bytes calldata data) external override { (address strat, bytes memory ext) = abi.decode(data, (address, bytes)); baseToken.safeTransfer(strat, baseToken.myBalance()); farmingToken.safeTransfer(strat, farmingToken.myBalance()); IStrategy(strat).execute(user, debt, ext); baseToken.safeTransfer(msg.sender, baseToken.myBalance()); } /// @dev Re-invest whatever the worker is working on. function reinvest() external override {} /// @dev Return the amount of wei to get back if we are to liquidate the position. function health(uint256 /*id*/) external override view returns (uint256) { return 0; } /// @dev Liquidate the given position to token. Send all token back to its Vault. function liquidate(uint256 /*id*/) external override {} /// @dev SetStretegy that be able to executed by the worker. function setStrategyOk(address[] calldata /*strats*/, bool /*isOk*/) external override {} /// @dev Set address that can be reinvest function setReinvestorOk(address[] calldata /*reinvestor*/, bool /*isOk*/) external override {} /// @dev LP token holds by worker function lpToken() external override view returns (IPancakePair) { return IPancakePair(address(0)); } /// @dev Return the trading path that worker is using for convert BTOKEN->...->FTOKEN function getPath() external override view returns (address[] memory) { return path; } /// @dev Return the inverse of the path that worker is using for convert BTOKEN->...->FTOKEN function getReversedPath() external override view returns (address[] memory) { address tmp; address[] memory reversedPath = path; for (uint i = 0; i < reversedPath.length / 2; i++) { tmp = reversedPath[i]; reversedPath[i] = reversedPath[reversedPath.length - i - 1]; reversedPath[reversedPath.length - i - 1] = tmp; } return reversedPath; } /// @dev Return the trading path that the worker is using to convert reward token to beneficial vault token function getRewardPath() external override view returns (address[] memory) { return rewardPath; } }
Return the trading path that the worker is using to convert reward token to beneficial vault token
function getRewardPath() external override view returns (address[] memory) { return rewardPath; }
6,401,689
./partial_match/3/0xF88038430085726183702b36a7D163a81528F7f1/sources/SwanStake.sol
id - the interestAccount id allows users to claim their invested tokens for 1 or 3 months from same function calculates the remaining interest to be transferred to the user transfers the invested amount as well as the remaining interest to the user. updates the user's staked balance to ZERO/
function claimInterestTokens(uint256 id) external whenNotPaused{ InterestAccount memory interestData = interestAccountDetails[msg.sender][id]; require (interestData.amount > 0,"Invested Amount is ZERO"); uint256 interestAmount = interestData.amount.mul(interestData.interestRate).div(100); uint256 remainingInterest = interestAmount.sub(totalPoolRewards[msg.sender][id]); uint256 tokensToSend = interestData.amount.add(remainingInterest); require(ERC20(swanTokenAddress).transfer(msg.sender, tokensToSend),"Token Transfer Failed"); userTotalStakes[msg.sender] -= interestData.amount; interestData.withdrawn = true; interestData.amount = 0; interestAccountDetails[msg.sender][id] = interestData; emit ClaimedInterestTokens(msg.sender,tokensToSend); }
5,069,539
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IDPexFeeAggregator.sol"; import "./interfaces/IDPexRouter.sol"; import "./abstracts/Governable.sol"; import "./abstracts/SafeGas.sol"; contract DPexFeeAggregator is IDPexFeeAggregator, Initializable, ContextUpgradeable, ReentrancyGuardUpgradeable, Governable, SafeGas { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; struct RewardSnapshot { uint256 time; uint256 totalPSI; mapping(address => uint256) userRewards; } //== Variables == EnumerableSet.AddressSet private _feeTokens; // all the token where a fee is deducted from on swap EnumerableSet.AddressSet private _tokenHolders; // all the tokens holder who will retrieve a share of fees mapping(address => uint256) private _claimed; // total amount of psi claimed by a user /** * @notice psi token contract */ address public psi; /** * @notice psi token contract */ address public WETH; /** * @notice percentage which get deducted from a swap (1 = 0.1%) */ uint256 public dpexFee; /** * @notice token fees gathered in the current period */ mapping(address => uint256) public tokensGathered; /** * @notice returns the latest reward snapshot id */ uint public latestRewardSnapshotId; /** * @notice all user reward snapshots taken */ mapping (uint => RewardSnapshot) public rewardSnapshots; //== CONSTRUCTOR == /** * @dev Initializes the contract setting the deployer as the initial Governor. */ function initialize(address _gov_contract, address _WETH, address _psi) public initializer { __Context_init(); __ReentrancyGuard_init(); super.initialize(_gov_contract); dpexFee = 1; latestRewardSnapshotId = 0; psi = _psi; WETH = _WETH; } //== MODIFIERS == modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'DPexFeeAggregator: EXPIRED'); _; } modifier onlyRouter() { require(router() == _msgSender(), "DPexFeeAggregator: ONLY_ROUTER_ALLOWED"); _; } //== VIEW == /** * @notice check if the current user is an token holder */ function isTokenHolder(address user) public override view returns (bool) { return _tokenHolders.contains(user); } /** * @notice return all the tokens where a fee is deducted from on swap */ function feeTokens() external override view returns (address[] memory) { address[] memory tokens = new address[](_feeTokens.length()); for(uint256 idx = 0; idx < _feeTokens.length(); idx++) { tokens[idx] = _feeTokens.at(idx); } return tokens; } /** * @notice checks if the token is a token where a fee is deducted from on swap * @param token fee token to check */ function isFeeToken(address token) public override view returns (bool) { return _feeTokens.contains(token); } /** * @notice returns the fee for the amount given * @param amount amount to calculate the fee for */ function calculateFee(uint256 amount) public override view returns (uint256 fee, uint256 amountLeft) { amountLeft = (amount.mul(1000).sub(amount.mul(dpexFee))).div(1000); fee = amount.sub(amountLeft); } /** * @notice returns the fee for the amount given, but only if the token is in the feetokens list * @param token token to check if it exists in the feetokens list * @param amount amount to calculate the fee for */ function calculateFee(address token, uint256 amount) external override view returns (uint256 fee, uint256 amountLeft) { if (!_feeTokens.contains(token)) { return (0, amount); } return calculateFee(amount); } /** * @notice returns the time and totalPSI from a snapshot * @param snapshotId the id from the snapshot to retrieve */ function getSnapshot(uint256 snapshotId) external override view returns (uint256 time, uint256 totalPsi) { require(snapshotId > 0 && snapshotId <= latestRewardSnapshotId, "DPexFeeAggregator: INVALID_SNAPSHOT_ID"); require(latestRewardSnapshotId > 0, "DPexFeeAggregator: NO_SNAPSHOT_TAKEN_YET"); time = rewardSnapshots[snapshotId].time; totalPsi = rewardSnapshots[snapshotId].totalPSI; } /** * @notice returns the rewards for a user from a snapshot * @param snapshotId the id from the snapshot to retrieve * @param user the address from the user to check rewards for */ function getSnapshotRewards(uint256 snapshotId, address user) external override view returns (uint256 rewards) { require(snapshotId > 0 && snapshotId <= latestRewardSnapshotId, "DPexFeeAggregator: INVALID_SNAPSHOT_ID"); require(user != address(0), "DPexFeeAggregator: NO_ADDRESS"); require(latestRewardSnapshotId > 0, "DPexFeeAggregator: NO_SNAPSHOT_TAKEN_YET"); rewards = rewardSnapshots[snapshotId].userRewards[user]; } /** * @notice returns the rewards for a user from a snapshot * @param user the address from the user to check rewards for */ function getTotalRewards(address user) public override view returns (uint256 rewards) { require(user != address(0), "DPexFeeAggregator: NO_ADDRESS"); require(latestRewardSnapshotId > 0, "DPexFeeAggregator: NO_SNAPSHOT_TAKEN_YET"); for(uint256 id = 1; id <= latestRewardSnapshotId; id++) { rewards += rewardSnapshots[id].userRewards[user]; } } /** * @notice returns the unclaimed rewards for a user from a snapshot * @param user the address from the user to check rewards for */ function getUnclaimedRewards(address user) public override view returns (uint256 rewards) { rewards = getTotalRewards(user).sub(_claimed[user]); } /** * @notice returns the claimed rewards for a user from a snapshot * @param user the address from the user to check rewards for */ function getClaimedRewards(address user) external override view returns (uint256 rewards) { rewards =_claimed[user]; } //== SET INTERNAL VARIABLES== /** * @notice adds a new token holder * @param user address of the token holder */ function addTokenHolder(address user) external override { require(user != address(0), "DPexFeeAggregator: TOKENHOLDER_NO_ADDRESS"); require(!isTokenHolder(user), "DPexFeeAggregator: ALREADY_TOKENHOLDER"); _tokenHolders.add(user); } /** * @notice removes the msg_sender token holder */ function removeTokenHolder() external override { require(isTokenHolder(_msgSender()), "DPexFeeAggregator: NOT_A_TOKENHOLDER"); _tokenHolders.remove(_msgSender()); } /** * @notice removes a token holder * @param user address of the token holder */ function removeTokenHolder(address user) external override onlyGovernor { require(user != address(0), "DPexFeeAggregator: TOKENHOLDER_NO_ADDRESS"); require(isTokenHolder(user), "DPexFeeAggregator: NOT_A_TOKENHOLDER"); _tokenHolders.remove(user); } /** * @notice add a token to deduct a fee for on swap * @param token fee token to add */ function addFeeToken(address token) public override onlyGovernor { require(!_feeTokens.contains(token), "DPexFeeAggregator: ALREADY_FEE_TOKEN"); _feeTokens.add(token); IERC20(token).approve(router(), 1e18); } /** * @notice remove a token to deduct a fee for on swap * @param token fee token to add */ function removeFeeToken(address token) external override onlyGovernor { require(_feeTokens.contains(token), "DPexFeeAggregator: NO_FEE_TOKEN"); _feeTokens.remove(token); } /** * @notice set the percentage which get deducted from a swap (1 = 0.1%) * @param fee percentage to set as fee */ function setDPexFee(uint256 fee) external override onlyGovernor { require(fee >= 0 && fee <= 200, "DPexFeeAggregator: FEE_MIN_0_MAX_20"); dpexFee = fee; } /** * @notice Adds the fee to the tokensGathered list. Transfer is done in the router * @param token fee token to check * @param fee fee to add to the tokensGathered list */ function addTokenFee(address token, uint256 fee) external override onlyRouter { require (_feeTokens.contains(token), "Token is not a feeToken"); tokensGathered[token] += fee; } /** * @notice takes a snapshot of the current moment and transfer non PSI token to PSI */ function takeSnapshotWithRewards(uint256 deadline) external override useCHI onlyGovernor ensure(deadline) { uint256 psiBalanceBefore = IERC20(psi).balanceOf(address(this)); sellFeesToPSI(); uint256 psiFeeBalance = IERC20(psi).balanceOf(address(this)).sub(psiBalanceBefore); if (tokensGathered[psi] > 0) { psiFeeBalance += tokensGathered[psi]; tokensGathered[psi] = 0; } uint256 totalPSIFromHolders = 0; for(uint256 idx = 0; idx < _tokenHolders.length(); idx++) { totalPSIFromHolders += IERC20(psi).balanceOf(_tokenHolders.at(idx)); } latestRewardSnapshotId++; rewardSnapshots[latestRewardSnapshotId].time = block.timestamp; rewardSnapshots[latestRewardSnapshotId].totalPSI = psiFeeBalance; for(uint256 idx = 0; idx < _tokenHolders.length(); idx++) { uint256 userReward = psiFeeBalance.div(totalPSIFromHolders .div(IERC20(psi).balanceOf(_tokenHolders.at(idx)))); if (userReward > 0) { rewardSnapshots[latestRewardSnapshotId].userRewards[_tokenHolders.at(idx)] = userReward; } } } function sellFeesToPSI() internal { for(uint256 idx = 0; idx < _feeTokens.length(); idx++) { address token = _feeTokens.at(idx); uint256 tokenBalance = IERC20(token).balanceOf(address(this)); if (token != WETH && token != psi && tokenBalance > 0) { tokensGathered[token] = 0; address[] memory path = new address[](2); path[0] = token; path[1] = WETH; IDPexRouter(router()).swapAggregatorToken(tokenBalance, path, address(this)); } } sellWETHToPSI(); } function sellWETHToPSI() internal { uint256 balance = IERC20(WETH).balanceOf(address(this)); if (balance <= 0) { return; } tokensGathered[WETH] = 0; address[] memory path = new address[](2); path[0] = WETH; path[1] = psi; IDPexRouter(router()).swapAggregatorToken(balance, path, address(this)); } /** * @notice Claims the rewards for a user */ function claim() external override nonReentrant useCHI { uint256 rewards = getUnclaimedRewards(_msgSender()); require (rewards > 0, "DPexFeeAggregator: NO_REWARDS_TO_CLAIM"); _claimed[_msgSender()] += rewards; IERC20(psi).safeTransfer(msg.sender, rewards); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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(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)); } } // 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, 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; } } // SPDX-License-Identifier: 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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IDPexFeeAggregator { function isTokenHolder(address user) external view returns (bool); function feeTokens() external view returns (address[] memory); function isFeeToken(address token) external view returns (bool); function calculateFee(uint256 amount) external view returns (uint256 fee, uint256 amountLeft); function calculateFee(address token, uint256 amount) external view returns (uint256 fee, uint256 amountLeft); function getSnapshot(uint256 snapshotId) external view returns (uint256 time, uint256 totalPsi); function getSnapshotRewards(uint256 snapshotId, address user) external view returns (uint256 rewards); function getTotalRewards(address user) external view returns (uint256 rewards); function getUnclaimedRewards(address user) external view returns (uint256 rewards); function getClaimedRewards(address user) external view returns (uint256 rewards); function addTokenHolder(address user) external; function removeTokenHolder() external; function removeTokenHolder(address user) external; function addFeeToken(address token) external; function removeFeeToken(address token) external; function setDPexFee(uint256 fee) external; function addTokenFee(address token, uint256 fee) external; function takeSnapshotWithRewards(uint256 deadline) external; function claim() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./uniswap/IUniswapV2Router02.sol"; import "./IGovernable.sol"; interface IDPexRouter is IUniswapV2Router02, IGovernable { function feeAggregator() external returns (address); function setfeeAggregator(address aggregator) external; function swapAggregatorToken( uint amountIn, address[] calldata path, address to ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IGovernable.sol"; abstract contract Governable is ContextUpgradeable, IGovernable { using Address for address; //== Variables == address public gov_contract; // contract governing the Token //== CONSTRUCTOR == /** * @dev Initializes the contract setting the deployer as the initial Governor. */ function initialize(address _gov_contract) internal virtual { require (_gov_contract.isContract(), "_gov_contract should be a contract"); gov_contract = _gov_contract; } //== MODIFIERS == modifier onlyMastermind() { require(isMastermind(_msgSender()), "Only mastermind is allowed"); _; } modifier onlyGovernor() { require(isGovernor(_msgSender()), "Only governor is allowed"); _; } modifier onlyPartner() { require(isPartner(_msgSender()), "Only partner is allowed"); _; } //== VIEW == function isMastermind(address _address) public override view returns (bool) { return IGovernable(gov_contract).isMastermind(_address); } function isGovernor(address _address) public override view returns (bool) { return IGovernable(gov_contract).isGovernor(_address); } function isPartner(address _address) public override view returns (bool) { return IGovernable(gov_contract).isPartner(_address); } function isUser(address _address) external override view returns (bool) { return IGovernable(gov_contract).isUser(_address); } function gasToken() public override view returns (address) { return IGovernable(gov_contract).gasToken(); } function enableGasPromotion() public override view returns (bool) { return IGovernable(gov_contract).enableGasPromotion(); } function router() public override view returns (address) { return IGovernable(gov_contract).router(); } //== SET INTERNAL VARIABLES== /** * @dev Change the governance contract * only mastermind is allowed to do this * @param _gov_contract Governance contract address */ function setGovernanceContract(address _gov_contract) external onlyMastermind { require(_gov_contract.isContract(), "_gov_contract should be a contract"); gov_contract = _gov_contract; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/ICHI.sol"; import "./Governable.sol"; abstract contract SafeGas is Governable { /** * @notice frees CHI from gas provider to reduce gas costs * @dev requires that gas provider has approved this contract to use their CHI */ modifier useCHI { uint256 gasStart = gasleft(); _; //uint256 gasSpent = 21000 + gasStart - gasleft() + (16 * msg.data.length); if (gasToken() != address(0)) { ICHI(gasToken()).freeFromUpTo(ensureGasProvider(), ((21000 + gasStart - gasleft() + (16 * msg.data.length)) + 14154) / 41947); } } /** * @notice make it possible to add a single gas provider */ function ensureGasProvider() internal view returns (address) { if (enableGasPromotion() && IERC20(gasToken()).balanceOf(address(this)) >= 1) { return address(this); } return msg.sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IUniswapV2Router01.sol"; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IGovernable { function gasToken() external view returns (address); function enableGasPromotion() external view returns (bool); function router() external view returns (address); function isMastermind(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isPartner(address _address) external view returns (bool); function isUser(address _address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IUniswapV2Router01 { function factory() external returns (address); function WETH() external 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 view returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external view returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >= 0.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: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ICHI is IERC20 { function freeFromUpTo(address _addr, uint256 _amount) external returns (uint256); }
== VIEW == check if the current user is an token holder/
function isTokenHolder(address user) public override view returns (bool) { return _tokenHolders.contains(user); }
5,915,915
pragma solidity >=0.5.0; //Adapters import './interfaces/IBaseUbeswapAdapter.sol'; //Interfaces import './interfaces/IERC20.sol'; import './interfaces/IPool.sol'; import './interfaces/ISettings.sol'; import './interfaces/IAddressResolver.sol'; import './interfaces/IFeePool.sol'; import './interfaces/IStakingRewards.sol'; import './interfaces/ILeveragedLiquidityPositionManager.sol'; import './interfaces/ILeveragedAssetPositionManager.sol'; //Libraries import './libraries/SafeMath.sol'; contract Pool is IPool, IERC20 { using SafeMath for uint; IAddressResolver public ADDRESS_RESOLVER; struct LiquidityPair { address tokenA; address tokenB; address farmAddress; uint numberOfLPTokens; } string public _name; uint public _totalSupply; address public _manager; uint public _performanceFee; //expressed as % address public _farmAddress; uint public _totalDeposits; mapping (address => uint) public _balanceOf; mapping (address => uint) public _deposits; mapping (address => mapping(address => uint)) public override allowance; //Asset positions mapping (uint => address) public _positionKeys; uint public numberOfPositions; mapping (address => uint) public positionToIndex; //maps to (index + 1), with index 0 representing position not found //Liquidity positions mapping (uint => LiquidityPair) public liquidityPositions; uint public numberOfLiquidityPositions; mapping (address => mapping(address => uint)) public liquidityPairToIndex; //maps to (index + 1), with index 0 representing position not found uint public totalNumberOfPositions; constructor(string memory name, uint performanceFee, address manager, IAddressResolver addressResolver) public { _name = name; _manager = manager; _performanceFee = performanceFee; ADDRESS_RESOLVER = addressResolver; } /* ========== VIEWS ========== */ /** * @dev Returns the name of the pool * @return string The name of the pool */ function name() public view override(IPool, IERC20) returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return ""; } function decimals() public view override returns (uint8) { return 18; } /** * @dev Returns the address of the pool's farm * @return address Address of the pool's farm */ function getFarmAddress() public view override returns (address) { return _farmAddress; } /** * @dev Return the pool manager's address * @return address Address of the pool's manager */ function getManagerAddress() public view override returns (address) { return _manager; } /** * @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value * @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions */ function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) { address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); address[] memory addresses = new address[](numberOfPositions); uint[] memory balances = new uint[](numberOfPositions); uint sum; //Calculate USD value of each asset position for (uint i = 0; i < numberOfPositions; i++) { balances[i] = IERC20(_positionKeys[i]).balanceOf(address(this)); addresses[i] = _positionKeys[i]; uint numberOfDecimals = IERC20(_positionKeys[i]).decimals(); uint USDperToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_positionKeys[i]); uint positionBalanceInUSD = balances[i].mul(USDperToken).div(10 ** numberOfDecimals); sum = sum.add(positionBalanceInUSD); } //Calculate USD value of each liquidity position for (uint i = 0; i < numberOfLiquidityPositions; i++) { LiquidityPair memory pair = liquidityPositions[i]; sum = sum.add(_calculateValueOfLPTokens(pair.tokenA, pair.tokenB, pair.numberOfLPTokens)); } //Calculate USD value of each leveraged asset position uint[] memory leveragedAssetPositions = ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).getUserPositions(address(this)); for (uint i = 0; i < leveragedAssetPositions.length; i++) { sum = sum.add(ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).getPositionValue(leveragedAssetPositions[i])); } //Calculate USD value of each leveraged liquidity position uint[] memory leveragedLiquidityPositions = ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getUserPositions(address(this)); for (uint i = 0; i < leveragedLiquidityPositions.length; i++) { sum = sum.add(ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getPositionValue(leveragedLiquidityPositions[i])); } return (addresses, balances, sum); } /** * @dev Returns the amount of cUSD the pool has to invest * @return uint Amount of cUSD the pool has available */ function getAvailableFunds() public view override returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); return IERC20(stableCoinAddress).balanceOf(address(this)); } /** * @dev Returns the value of the pool in USD * @return uint Value of the pool in USD */ function getPoolBalance() public view override returns (uint) { (,, uint positionBalance) = getPositionsAndTotal(); return positionBalance; } /** * @dev Returns the balance of the user in USD * @return uint Balance of the user in USD */ function getUSDBalance(address user) public view override returns (uint) { require(user != address(0), "Invalid address"); uint poolBalance = getPoolBalance(); return poolBalance.mul(_balanceOf[user]).div(_totalSupply); } /** * @dev Returns the number of LP tokens the user has * @param user Address of the user * @return uint Number of LP tokens the user has */ function balanceOf(address user) public view override(IPool, IERC20) returns (uint) { require(user != address(0), "Invalid user address"); return _balanceOf[user]; } /** * @dev Returns the total supply of LP tokens in the pool * @return uint Total supply of LP tokens */ function totalSupply() public view override returns (uint) { return _totalSupply; } /** * @dev Returns the pool's performance fee * @return uint The pool's performance fee */ function getPerformanceFee() public view override returns (uint) { return _performanceFee; } /* ========== MUTATIVE FUNCTIONS ========== */ function approve(address spender, uint value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) public override returns (bool) { if (allowance[from][msg.sender] > 0) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev Deposits the given USD amount into the pool * @notice Call cUSD.approve() before calling this function * @param amount Amount of USD to deposit into the pool */ function deposit(uint amount) public override { require(amount > 0, "Pool: Deposit must be greater than 0"); uint poolBalance = getPoolBalance(); uint numberOfLPTokens = (_totalSupply > 0) ? _totalSupply.mul(amount).div(poolBalance) : amount; _deposits[msg.sender] = _deposits[msg.sender].add(amount); _totalDeposits = _totalDeposits.add(amount); _balanceOf[msg.sender] = _balanceOf[msg.sender].add(numberOfLPTokens); _totalSupply = _totalSupply.add(numberOfLPTokens); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); IERC20(stableCoinAddress).transferFrom(msg.sender, address(this), amount); //Add cUSD to position keys if it's not there already _addPositionKey(stableCoinAddress); emit Deposit(address(this), msg.sender, amount, block.timestamp); } /** * @dev Withdraws the given USD amount on behalf of the user * @notice The withdrawal is done using pool's assets at time of withdrawal. This avoids the exchange fees and slippage from exchanging pool's assets back to cUSD or TGEN. * @param amount Amount of USD to withdraw from the pool */ function withdraw(uint amount) public override { require(amount > 0, "Pool: Withdrawal must be greater than 0"); uint poolBalance = getPoolBalance(); uint USDBalance = poolBalance.mul(_balanceOf[msg.sender]).div(_totalSupply); require(USDBalance >= amount, "Pool: Not enough funds to withdraw"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); //Transfer leveraged positions ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).bulkTransferTokens(msg.sender, amount, poolBalance); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).bulkTransferTokens(msg.sender, amount, poolBalance); //Reduce liquidity positions for (uint i = 0; i < numberOfLiquidityPositions; i++) { LiquidityPair memory liquidityPosition = liquidityPositions[i]; removeLiquidity(liquidityPosition.tokenA, liquidityPosition.tokenB, liquidityPosition.farmAddress, liquidityPosition.numberOfLPTokens.mul(amount).div(poolBalance)); } uint profit = (USDBalance > _deposits[msg.sender]) ? USDBalance.sub(_deposits[msg.sender]) : 0; uint fee = profit.mul(amount).div(USDBalance); //Multiply by ratio of withdrawal amount to user's USD balance fee = fee.mul(_performanceFee).div(100); //Update state variables uint depositAmount = _deposits[msg.sender].mul(amount).div(USDBalance); uint numberOfLPTokens = _balanceOf[msg.sender].mul(amount).div(USDBalance); _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(numberOfLPTokens); _totalSupply = _totalSupply.sub(numberOfLPTokens); _deposits[msg.sender] = _deposits[msg.sender].sub(depositAmount); _totalDeposits = _totalDeposits.sub(depositAmount); //Withdraw user's portion of pool's assets for (uint i = 0; i < numberOfPositions; i++) { uint positionBalance = IERC20(_positionKeys[i]).balanceOf(address(this)); //Number of asset's tokens uint amountToTransferToUser = positionBalance.mul(amount.sub(fee)).div(poolBalance); //Multiply by ratio of withdrawal amount after fee to pool's USD balance uint amountToTransferToManager = positionBalance.mul(fee).div(poolBalance); IERC20(_positionKeys[i]).transfer(msg.sender, amountToTransferToUser); IERC20(_positionKeys[i]).transfer(_manager, amountToTransferToManager); //Remove position keys if pool is liquidated if (_totalSupply == 0) { _removePositionKey(_positionKeys[i]); } } //Set numberOfPositions to 0 if pool is liquidated if (_totalSupply == 0) { numberOfPositions = 0; } emit Withdraw(address(this), msg.sender, amount, block.timestamp); } /* ========== RESTRICTED FUNCTIONS ========== */ /** * @dev Places an order to buy/sell the given currency * @param currencyKey Address of currency to trade * @param buyOrSell Whether the user is buying or selling * @param numberOfTokens Number of tokens of the given currency */ function placeOrder(address currencyKey, bool buyOrSell, uint numberOfTokens) public override onlyPoolManager { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); require(numberOfTokens > 0, "Pool: Number of tokens must be greater than 0"); require(currencyKey != address(0), "Pool: Invalid currency key"); require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(currencyKey), "Pool: Currency key is not available"); uint numberOfDecimals = IERC20(currencyKey).decimals(); uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(currencyKey); uint numberOfTokensReceived; uint amountInUSD = numberOfTokens.mul(tokenToUSD).div(10 ** numberOfDecimals); //buying if (buyOrSell) { require(getAvailableFunds() >= amountInUSD, "Pool: Not enough funds"); //Add to position keys if no position yet _addPositionKey(currencyKey); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, amountInUSD); numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromPool(stableCoinAddress, currencyKey, amountInUSD, numberOfTokens); } //selling else { uint positionIndex = positionToIndex[currencyKey]; require(positionIndex > 0, "Pool: Don't have a position in this currency"); require(IERC20(currencyKey).balanceOf(address(this)) >= numberOfTokens, "Pool: Not enough tokens in this currency"); IERC20(currencyKey).transfer(baseUbeswapAdapterAddress, numberOfTokens); numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromPool(currencyKey, stableCoinAddress, numberOfTokens, amountInUSD); //remove position key if no funds left in currency _removePositionKey(currencyKey); } emit PlacedOrder(address(this), currencyKey, buyOrSell, numberOfTokens, block.timestamp); } /** * @dev Adds liquidity for the two given tokens * @param tokenA First token in pair * @param tokenB Second token in pair * @param amountA Amount of first token * @param amountB Amount of second token * @param farmAddress The token pair's farm address */ function addLiquidity(address tokenA, address tokenB, uint amountA, uint amountB, address farmAddress) public override onlyPoolManager { require(tokenA != address(0), "Pool: invalid address for tokenA"); require(tokenB != address(0), "Pool: invalid address for tokenB"); require(amountA > 0, "Pool: amountA must be greater than 0"); require(amountB > 0, "Pool: amountB must be greater than 0"); require(IERC20(tokenA).balanceOf(address(this)) >= amountA, "Pool: not enough tokens invested in tokenA"); require(IERC20(tokenB).balanceOf(address(this)) >= amountB, "Pool: not enough tokens invested in tokenB"); //Check if farm exists for the token pair address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress); address pairAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB); require(stakingTokenAddress == pairAddress, "Pool: stakingTokenAddress does not match pairAddress"); //Add liquidity to Ubeswap pool and stake LP tokens into associated farm uint numberOfLPTokens = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).addLiquidity(tokenA, tokenB, amountA, amountB); IStakingRewards(stakingTokenAddress).stake(numberOfLPTokens); //Update liquidity positions (address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA); if (liquidityPairToIndex[token0][token1] == 0) { liquidityPositions[numberOfLiquidityPositions] = LiquidityPair(token0, token1, farmAddress, numberOfLPTokens); liquidityPairToIndex[token0][token1] = numberOfLiquidityPositions; numberOfLiquidityPositions = numberOfLiquidityPositions.add(1); } else { uint index = liquidityPairToIndex[token0][token1]; liquidityPositions[index].numberOfLPTokens = liquidityPositions[index].numberOfLPTokens.add(numberOfLPTokens); } //Update position keys _removePositionKey(tokenA); _removePositionKey(tokenB); emit AddedLiquidity(address(this), tokenA, tokenB, amountA, amountB, numberOfLPTokens, block.timestamp); } /** * @dev Removes liquidity for the two given tokens * @param tokenA First token in pair * @param tokenB Second token in pair * @param farmAddress The token pair's farm address * @param numberOfLPTokens Number of LP tokens to remove from the farm */ function removeLiquidity(address tokenA, address tokenB, address farmAddress, uint numberOfLPTokens) public override onlyPoolManager { require(tokenA != address(0), "Pool: invalid address for tokenA"); require(tokenB != address(0), "Pool: invalid address for tokenB"); //Check if pool has enough LP tokens in the farm (address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA); uint index = liquidityPairToIndex[token0][token1]; require(liquidityPositions[index].numberOfLPTokens >= numberOfLPTokens, "Pool: not enough LP tokens to unstake"); //Check if farmAddress is valid address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); require(IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "Invalid farm address"); //Withdraw all LP tokens from the farm and claim available UBE rewards //Need to restake remaining LP tokens later IStakingRewards(farmAddress).exit(); //Check for UBE balance and update position keys if UBE not currently in postion keys address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE"); _addPositionKey(UBE); //Remove liquidity from Ubeswap liquidity pool (uint amountA, uint amountB) = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).removeLiquidity(tokenA, tokenB, numberOfLPTokens); //Update position keys _addPositionKey(tokenA); _addPositionKey(tokenB); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); //Update liquidity positions liquidityPositions[index].numberOfLPTokens = liquidityPositions[index].numberOfLPTokens.sub(numberOfLPTokens); //Restake remaining LP tokens IStakingRewards(farmAddress).stake(liquidityPositions[index].numberOfLPTokens); emit RemovedLiquidity(address(this), tokenA, tokenB, numberOfLPTokens, amountA, amountB, block.timestamp); } /** * @dev Collects available UBE rewards for the given Ubeswap farm * @param farmAddress The token pair's farm address */ function claimUbeswapRewards(address farmAddress) public override onlyPoolManager { //Check if farmAddress is valid address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); require(IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "Invalid farm address"); //Check if pool has tokens staked in farm require(IStakingRewards(farmAddress).balanceOf(address(this)) > 0, "Pool: no tokens staked in farm"); //Claim available UBE rewards IStakingRewards(farmAddress).getReward(); //Check for UBE balance and update position keys if UBE not currently in postion keys address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE"); _addPositionKey(UBE); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); emit ClaimedUbeswapRewards(address(this), farmAddress, block.timestamp); } /** * @dev Opens a new leveraged asset position; swaps cUSD for specified asset * @notice LeveragedAssetPositionManager checks if currency is supported * @param underlyingAsset Address of the leveraged asset * @param collateral Amount of cUSD to use as collateral * @param amountToBorrow Amount of cUSD to borrow */ function openLeveragedAssetPosition(address underlyingAsset, uint collateral, uint amountToBorrow) public override onlyPoolManager { require(getAvailableFunds() >= collateral, "Pool: not enough funds"); require(underlyingAsset != address(0), "Pool: invalid asset address"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, collateral); ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).openPosition(underlyingAsset, collateral, amountToBorrow); totalNumberOfPositions = totalNumberOfPositions.add(1); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); emit OpenedLeveragedAssetPosition(address(this), underlyingAsset, collateral, amountToBorrow, block.timestamp); } /** * @dev Reduces the size of a leveraged asset position * @notice LeveragedAssetPositionManager checks if pool is owner of position at given index * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of tokens to sell */ function reduceLeveragedAssetPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).reducePosition(positionIndex, numberOfTokens); emit ReducedLeveragedAssetPosition(address(this), positionIndex, numberOfTokens, block.timestamp); } /** * @dev Closes a leveraged asset position * @notice LeveragedAssetPositionManager checks if pool is owner of position at given index * @param positionIndex Index of the leveraged position in array of leveraged positions */ function closeLeveragedAssetPosition(uint positionIndex) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).closePosition(positionIndex); totalNumberOfPositions = totalNumberOfPositions.sub(1); emit ClosedLeveragedAssetPosition(address(this), positionIndex, block.timestamp); } /** * @dev Adds collateral to the leveraged asset position * @notice LeveragedAssetPositionManager checks if pool is owner of position at given index * @param positionIndex Index of the leveraged position in array of leveraged positions * @param amountOfUSD Amount of cUSD to add as collateral */ function addCollateralToLeveragedAssetPosition(uint positionIndex, uint amountOfUSD) public override onlyPoolManager { require(getAvailableFunds() >= amountOfUSD, "Pool: not enough funds"); require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, amountOfUSD); ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).addCollateral(positionIndex, amountOfUSD); emit AddedCollateralToLeveragedAssetPosition(address(this), positionIndex, amountOfUSD, block.timestamp); } /** * @dev Removes collateral from the leveraged asset position * @notice LeveragedAssetPositionManager checks if pool is owner of position at given index * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of asset tokens to remove as collateral */ function removeCollateralFromLeveragedAssetPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).removeCollateral(positionIndex, numberOfTokens); emit RemovedCollateralFromLeveragedAssetPosition(address(this), positionIndex, numberOfTokens, block.timestamp); } /** * @dev Opens a new leveraged liquidity position; swaps cUSD for specified asset * @notice LeveragedLiquidityPositionManager checks if tokens are supported * @notice LeveragedLiquidityPositionManager checks if farmAddress is supported * @param tokenA Address of first token in pair * @param tokenB Address of second token in pair * @param collateral Amount of cUSD to use as collateral * @param amountToBorrow Amount of cUSD to borrow * @param farmAddress Address of token pair's Ubeswap farm */ function openLeveragedLiquidityPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) public override onlyPoolManager { require(getAvailableFunds() >= collateral, "Pool: not enough funds"); require(tokenA != address(0), "Pool: invalid tokenA address"); require(tokenB != address(0), "Pool: invalid tokenB address"); require(farmAddress != address(0), "Pool: invalid farm address"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, collateral); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).openPosition(tokenA, tokenB, collateral, amountToBorrow, farmAddress); totalNumberOfPositions = totalNumberOfPositions.add(1); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); emit OpenedLeveragedLiquidityPosition(address(this), tokenA, tokenB, collateral, amountToBorrow, farmAddress, block.timestamp); } /** * @dev Reduces the size of a leveraged liquidity position * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of tokens to sell */ function reduceLeveragedLiquidityPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).reducePosition(positionIndex, numberOfTokens); emit ReducedLeveragedLiquidityPosition(address(this), positionIndex, numberOfTokens, block.timestamp); } /** * @dev Closes a leveraged liquidity position * @param positionIndex Index of the leveraged position in array of leveraged positions */ function closeLeveragedLiquidityPosition(uint positionIndex) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).closePosition(positionIndex); totalNumberOfPositions = totalNumberOfPositions.sub(1); emit ClosedLeveragedLiquidityPosition(address(this), positionIndex, block.timestamp); } /** * @dev Adds collateral to the leveraged liquidity position * @param positionIndex Index of the leveraged position in array of leveraged positions * @param amountOfUSD Amount of cUSD to add as collateral */ function addCollateralToLeveragedLiquidityPosition(uint positionIndex, uint amountOfUSD) public override onlyPoolManager { require(getAvailableFunds() >= amountOfUSD, "Pool: not enough funds"); require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards"); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, amountOfUSD); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).addCollateral(positionIndex, amountOfUSD); emit AddedCollateralToLeveragedLiquidityPosition(address(this), positionIndex, amountOfUSD, block.timestamp); } /** * @dev Removes collateral from the leveraged liquidity position * @param positionIndex Index of the leveraged position in array of leveraged positions * @param numberOfTokens Number of asset tokens to remove as collateral */ function removeCollateralFromLeveragedLiquidityPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).removeCollateral(positionIndex, numberOfTokens); emit RemovedCollateralFromLeveragedLiquidityPosition(address(this), positionIndex, numberOfTokens, block.timestamp); } /** * @dev Claims available UBE rewards for the leveraged liquidity position * @param positionIndex Index of the leveraged position in array of leveraged positions */ function getReward(uint positionIndex) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getReward(positionIndex); //Check for UBE balance and update position keys if UBE not currently in postion keys address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE"); _addPositionKey(UBE); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); emit RewardPaid(address(this), positionIndex, block.timestamp); } /** * @dev Updates the pool's farm address * @param farmAddress Address of the pool's farm */ function setFarmAddress(address farmAddress) public override onlyPoolFactory { require(farmAddress != address(0), "Invalid farm address"); _farmAddress = farmAddress; } /** * @dev Decrement's the totalNumberOfPositions * @notice Called from liquidate() in LeveragedAssetPositionManager or LeveragedLiquidityPositionManager */ function decrementTotalPositionCount() public override onlyLeveragedPositionManager { totalNumberOfPositions = totalNumberOfPositions.sub(1); } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Calculates the USD value of a token pair * @param tokenA First token in the pair * @param tokenB Second token in the pair * @param numberOfLPTokens Number of LP tokens in the pair */ function _calculateValueOfLPTokens(address tokenA, address tokenB, uint numberOfLPTokens) internal view returns (uint) { require(tokenA != address(0), "Pool: invalid address for tokenA"); require(tokenB != address(0), "Pool: invalid address for tokenB"); if (numberOfLPTokens == 0) { return 0; } address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter"); (uint amountA, uint amountB) = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getTokenAmountsFromPair(tokenA, tokenB, numberOfLPTokens); uint numberOfDecimalsA = IERC20(tokenA).decimals(); uint USDperTokenA = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(tokenA); uint USDBalanceA = amountA.mul(USDperTokenA).div(10 ** numberOfDecimalsA); uint numberOfDecimalsB = IERC20(tokenB).decimals(); uint USDperTokenB = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(tokenB); uint USDBalanceB = amountB.mul(USDperTokenB).div(10 ** numberOfDecimalsB); return USDBalanceA.add(USDBalanceB); } /** * @dev Adds the given currency to position keys * @param currency Address of token to add */ function _addPositionKey(address currency) internal { require(currency != address(0), "Pool: invalid asset address"); //Add token to positionKeys if balance > 0 and not currently in positionKeys if (IERC20(currency).balanceOf(address(this)) > 0 && positionToIndex[currency] == 0) { positionToIndex[currency] = numberOfPositions; _positionKeys[numberOfPositions] = currency; numberOfPositions = numberOfPositions.add(1); totalNumberOfPositions = totalNumberOfPositions.add(1); } } /** * @dev Removes the given currency to position keys * @param currency Address of token to remove */ function _removePositionKey(address currency) internal { require(currency != address(0), "Pool: invalid asset address"); //Remove currency from positionKeys if no balance left if (IERC20(currency).balanceOf(address(this)) == 0) { _positionKeys[positionToIndex[currency]] = _positionKeys[numberOfPositions - 1]; positionToIndex[_positionKeys[numberOfPositions - 1]] = positionToIndex[currency]; delete _positionKeys[numberOfPositions - 1]; delete positionToIndex[currency]; numberOfPositions = numberOfPositions.sub(1); totalNumberOfPositions = totalNumberOfPositions.sub(1); } } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(from, to, value); } /* ========== MODIFIERS ========== */ modifier onlyPoolFactory() { address poolFactoryAddress = ADDRESS_RESOLVER.getContractAddress("PoolFactory"); require(msg.sender == poolFactoryAddress, "Pool: Only PoolFactory contract can call this function"); _; } modifier onlyPoolManager() { require(msg.sender == _manager, "Pool: Only pool's manager can call this function"); _; } modifier onlyLeveragedPositionManager() { address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"); require(msg.sender == leveragedLiquidityPositionManagerAddress || msg.sender == leveragedAssetPositionManagerAddress, "Pool: Only a leverage position manager contract can call this function"); _; } /* ========== EVENTS ========== */ event Deposit(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp); event Withdraw(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp); event PlacedOrder(address indexed poolAddress, address indexed currencyKey, bool buyOrSell, uint amount, uint timestamp); event AddedLiquidity(address indexed poolAddress, address tokenA, address tokenB, uint amountA, uint amountB, uint numberOfLPTokensReceived, uint timestamp); event RemovedLiquidity(address indexed poolAddress, address tokenA, address tokenB, uint numberOfLPTokens, uint amountAReceived, uint amountBReceived, uint timestamp); event ClaimedUbeswapRewards(address indexed poolAddress, address farmAddress, uint timestamp); //Leveraged asset positions event OpenedLeveragedAssetPosition(address indexed poolAddress, address indexed underlyingAsset, uint collateral, uint numberOfTokensBorrowed, uint timestamp); event ReducedLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint numberOfTokens, uint timestamp); event ClosedLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint timestamp); event AddedCollateralToLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralAdded, uint timestamp); event RemovedCollateralFromLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralRemoved, uint timestamp); //Leveraged liquidity positions event OpenedLeveragedLiquidityPosition(address indexed poolAddress, address tokenA, address tokenB, uint collateral, uint numberOfTokensBorrowed, address farmAddress, uint timestamp); event ReducedLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint numberOfTokens, uint timestamp); event ClosedLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint timestamp); event AddedCollateralToLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralAdded, uint timestamp); event RemovedCollateralFromLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralRemoved, uint timestamp); event RewardPaid(address indexed poolAddress, uint positionIndex, uint timestamp); }
Claims available UBE rewards for the leveraged liquidity position positionIndex Index of the leveraged position in array of leveraged positions/Check for UBE balance and update position keys if UBE not currently in postion keys
function getReward(uint positionIndex) public override onlyPoolManager { require(positionIndex > 0, "Pool: positionIndex must be greater than 0"); address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager"); ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getReward(positionIndex); address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE"); _addPositionKey(UBE); require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions"); emit RewardPaid(address(this), positionIndex, block.timestamp); }
6,365,237
./full_match/4/0x011F0DA68ce3F80b2C8DCd6D94B2f36280ff3b6f/sources/contracts/ico.sol
function called when sending eth to the contractrequire(icoState == State.running);require(amount >= minInvestment);require(raisedAmount <= hardCap);
function invest() payable public returns(bool){ icoState = getCurrentState(); balances[admin] = msg.value; uint tokens = (msg.value / tokenPrice) * 10**18; _mint(msg.sender,tokens); metrics.soldToday += tokens; uint treasury = (msg.value).div(2); treasuryRaised += treasury; balances[treasuryAddress] = balances[treasuryAddress] + treasury; uint core = (msg.value).div(2); balances[coreAddress] = balances[coreAddress] + core; uint tkCore = tokens.div(10); _mint(coreAddress, tkCore); emit Invest(msg.sender, msg.value, tokens); return true; }
740,474
pragma solidity 0.5.14; pragma experimental ABIEncoderV2; import {BlockHeaderMerkleParts} from "./BlockHeaderMerkleParts.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {Ownable} from "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import {IAVLMerklePath} from "./IAVLMerklePath.sol"; import {TMSignature} from "./TMSignature.sol"; import {Utils} from "./Utils.sol"; import {IBridge} from "./IBridge.sol"; /// @title Bridge <3 BandChain D3N /// @author Band Protocol Team contract Bridge is IBridge, Ownable { using BlockHeaderMerkleParts for BlockHeaderMerkleParts.Data; using IAVLMerklePath for IAVLMerklePath.Data; using TMSignature for TMSignature.Data; using SafeMath for uint256; /// Mapping from block height to the hash of "zoracle" iAVL Merkle tree. mapping(uint256 => bytes32) public oracleStates; /// Mapping from an address to its voting power. mapping(address => uint256) public validatorPowers; /// The total voting power of active validators currently on duty. uint256 public totalValidatorPower; struct ValidatorWithPower { address addr; uint256 power; } /// Initializes an oracle bridge to BandChain. /// @param _validators The initial set of BandChain active validators. constructor(ValidatorWithPower[] memory _validators) public { for (uint256 idx = 0; idx < _validators.length; ++idx) { ValidatorWithPower memory validator = _validators[idx]; require( validatorPowers[validator.addr] == 0, "DUPLICATION_IN_INITIAL_VALIDATOR_SET" ); validatorPowers[validator.addr] = validator.power; totalValidatorPower = totalValidatorPower.add(validator.power); } } /// Update validator powers by owner. /// @param _validators The changed set of BandChain validators. function updateValidatorPowers(ValidatorWithPower[] memory _validators) public onlyOwner { for (uint256 idx = 0; idx < _validators.length; ++idx) { ValidatorWithPower memory validator = _validators[idx]; totalValidatorPower = totalValidatorPower.sub( validatorPowers[validator.addr] ); validatorPowers[validator.addr] = validator.power; totalValidatorPower = totalValidatorPower.add(validator.power); } } /// Relays a new oracle state to the bridge contract. /// @param _blockHeight The height of block to relay to this bridge contract. /// @param _oracleIAVLStateHash Hash of iAVL Merkle that represents the state of oracle store. /// @param _otherStoresMerkleHash Hash of internal Merkle node for other Tendermint storages. /// @param _merkleParts Extra merkle parts to compute block hash. See BlockHeaderMerkleParts lib. /// @param _signedDataPrefix Prefix data prepended prior to signing block hash. /// @param _signatures The signatures signed on this block, sorted alphabetically by address. function relayOracleState( uint256 _blockHeight, bytes32 _oracleIAVLStateHash, bytes32 _otherStoresMerkleHash, bytes32 _supplyStoresMerkleHash, BlockHeaderMerkleParts.Data memory _merkleParts, bytes memory _signedDataPrefix, TMSignature.Data[] memory _signatures ) public { // Computes Tendermint's application state hash at this given block. AppHash is actually a // Merkle hash on muliple stores. Luckily, we only care about "zoracle" tree and all other // stores can just be combined into one bytes32 hash off-chain. // // ____________appHash_________ // / \ // ____otherStoresMerkleHash ____ ___innerHash___ // / \ / \ // _____ h5 ______ ______ h6 _______ supply zoracle // / \ / \ // h1 h2 h3 h4 // /\ /\ /\ /\ // acc distribution gov main mint params slashing staking bytes32 appHash = Utils.merkleInnerHash( _otherStoresMerkleHash, Utils.merkleInnerHash( _supplyStoresMerkleHash, Utils.merkleLeafHash( abi.encodePacked( hex"077a6f7261636c6520", // uint8(7) + "zoracle" + uint8(32) sha256( abi.encodePacked( sha256(abi.encodePacked(_oracleIAVLStateHash)) ) ) ) ) ) ); // Computes Tendermint's block header hash at this given block. bytes32 blockHeader = _merkleParts.getBlockHeader( appHash, _blockHeight ); // Counts the total number of valid signatures signed by active validators. address lastSigner = address(0); uint256 sumVotingPower = 0; for (uint256 idx = 0; idx < _signatures.length; ++idx) { address signer = _signatures[idx].recoverSigner( blockHeader, _signedDataPrefix ); require(signer > lastSigner, "INVALID_SIGNATURE_SIGNER_ORDER"); sumVotingPower = sumVotingPower.add(validatorPowers[signer]); lastSigner = signer; } // Verifies that sufficient validators signed the block and saves the oracle state. require( sumVotingPower.mul(3) > totalValidatorPower.mul(2), "INSUFFICIENT_VALIDATOR_SIGNATURES" ); oracleStates[_blockHeight] = _oracleIAVLStateHash; } /// Helper struct to workaround Solidity's "stack too deep" problem. struct VerifyOracleDataLocalVariables { bytes encodedVarint; bytes32 dataHash; } /// Decodes the encoded result and returns back the decoded data which is the data and its context. /// @param _encodedData The encoded of result and its context. function decodeResult(bytes memory _encodedData) public pure returns (VerifyOracleDataResult memory) { require(_encodedData.length > 40, "INPUT_MUST_BE_LONGER_THAN_40_BYTES"); VerifyOracleDataResult memory result; assembly { mstore( add(result, 0x20), and(mload(add(_encodedData, 0x08)), 0xffffffffffffffff) ) mstore( add(result, 0x40), and(mload(add(_encodedData, 0x10)), 0xffffffffffffffff) ) mstore( add(result, 0x60), and(mload(add(_encodedData, 0x18)), 0xffffffffffffffff) ) mstore( add(result, 0x80), and(mload(add(_encodedData, 0x20)), 0xffffffffffffffff) ) mstore( add(result, 0xa0), and(mload(add(_encodedData, 0x28)), 0xffffffffffffffff) ) } bytes memory data = new bytes(_encodedData.length - 40); uint256 dataLengthInWords = ((data.length - 1) / 32) + 1; for (uint256 i = 0; i < dataLengthInWords; i++) { assembly { mstore( add(data, add(0x20, mul(i, 0x20))), mload(add(_encodedData, add(0x48, mul(i, 0x20)))) ) } } result.data = data; return result; } /// Verifies that the given data is a valid data on BandChain as of the given block height. /// @param _blockHeight The block height. Someone must already relay this block. /// @param _data The data to verify, with the format similar to what on the blockchain store. /// @param _requestId The ID of request for this data piece. /// @param _version Lastest block height that the data node was updated. /// @param _merklePaths Merkle proof that shows how the data leave is part of the oracle iAVL. function verifyOracleData( uint256 _blockHeight, bytes memory _data, uint64 _requestId, uint64 _oracleScriptId, bytes memory _params, uint256 _version, IAVLMerklePath.Data[] memory _merklePaths ) public view returns (VerifyOracleDataResult memory) { bytes32 oracleStateRoot = oracleStates[_blockHeight]; require( oracleStateRoot != bytes32(uint256(0)), "NO_ORACLE_ROOT_STATE_DATA" ); // Computes the hash of leaf node for iAVL oracle tree. VerifyOracleDataLocalVariables memory vars; vars.encodedVarint = Utils.encodeVarintSigned(_version); vars.dataHash = sha256(_data); bytes32 currentMerkleHash = sha256( abi.encodePacked( uint8(0), // Height of tree (only leaf node) is 0 (signed-varint encode) uint8(2), // Size of subtree is 1 (signed-varint encode) vars.encodedVarint, uint8(17 + _params.length), // Size of data key (1-byte constant 0x01 + 8-byte request ID + 8-byte oracleScriptId + length of params) uint8(255), // Constant 0xff prefix data request info storage key _requestId, _oracleScriptId, _params, uint8(32), // Size of data hash vars.dataHash ) ); // Goes step-by-step computing hash of parent nodes until reaching root node. for (uint256 idx = 0; idx < _merklePaths.length; ++idx) { currentMerkleHash = _merklePaths[idx].getParentHash( currentMerkleHash ); } // Verifies that the computed Merkle root matches what currently exists. require( currentMerkleHash == oracleStateRoot, "INVALID_ORACLE_DATA_PROOF" ); VerifyOracleDataResult memory result = decodeResult(_data); result.params = _params; result.oracleScriptId = _oracleScriptId; return result; } /// Performs oracle state relay and oracle data verification in one go. The caller submits /// the encoded proof and receives back the decoded data, ready to be validated and used. /// @param _data The encoded data for oracle state relay and data verification. function relayAndVerify(bytes calldata _data) external returns (VerifyOracleDataResult memory result) { (bytes memory relayData, bytes memory verifyData) = abi.decode( _data, (bytes, bytes) ); (bool relayOk, ) = address(this).call( abi.encodePacked(this.relayOracleState.selector, relayData) ); require(relayOk, "RELAY_ORACLE_STATE_FAILED"); (bool verifyOk, bytes memory verifyResult) = address(this).staticcall( abi.encodePacked(this.verifyOracleData.selector, verifyData) ); require(verifyOk, "VERIFY_ORACLE_DATA_FAILED"); return abi.decode(verifyResult, (VerifyOracleDataResult)); } }
Relays a new oracle state to the bridge contract. _blockHeight The height of block to relay to this bridge contract. _oracleIAVLStateHash Hash of iAVL Merkle that represents the state of oracle store. _otherStoresMerkleHash Hash of internal Merkle node for other Tendermint storages. _merkleParts Extra merkle parts to compute block hash. See BlockHeaderMerkleParts lib. _signedDataPrefix Prefix data prepended prior to signing block hash. _signatures The signatures signed on this block, sorted alphabetically by address. Computes Tendermint's application state hash at this given block. AppHash is actually a Merkle hash on muliple stores. Luckily, we only care about "zoracle" tree and all other stores can just be combined into one bytes32 hash off-chain. ____________appHash_________ / \ ____otherStoresMerkleHash ____ ___innerHash___ / \ / \ _____ h5 ______ ______ h6 _______ supply zoracle / \ / \ h1 h2 h3 h4 /\ /\ /\ /\ acc distribution gov main mint params slashing staking Computes Tendermint's block header hash at this given block. Counts the total number of valid signatures signed by active validators.
function relayOracleState( uint256 _blockHeight, bytes32 _oracleIAVLStateHash, bytes32 _otherStoresMerkleHash, bytes32 _supplyStoresMerkleHash, BlockHeaderMerkleParts.Data memory _merkleParts, bytes memory _signedDataPrefix, TMSignature.Data[] memory _signatures ) public { bytes32 appHash = Utils.merkleInnerHash( _otherStoresMerkleHash, Utils.merkleInnerHash( _supplyStoresMerkleHash, Utils.merkleLeafHash( abi.encodePacked( sha256( abi.encodePacked( sha256(abi.encodePacked(_oracleIAVLStateHash)) ) ) ) ) ) ); bytes32 blockHeader = _merkleParts.getBlockHeader( appHash, _blockHeight ); address lastSigner = address(0); uint256 sumVotingPower = 0; for (uint256 idx = 0; idx < _signatures.length; ++idx) { address signer = _signatures[idx].recoverSigner( blockHeader, _signedDataPrefix ); require(signer > lastSigner, "INVALID_SIGNATURE_SIGNER_ORDER"); sumVotingPower = sumVotingPower.add(validatorPowers[signer]); lastSigner = signer; } sumVotingPower.mul(3) > totalValidatorPower.mul(2), "INSUFFICIENT_VALIDATOR_SIGNATURES" ); oracleStates[_blockHeight] = _oracleIAVLStateHash; }
12,997,137
./full_match/97/0x0342ABBde45C187087895C21249d484E164b5e44/sources/project_/contracts/diamond/libraries/LibPairsManager.sol
todo: 校验 base 标的对应的价格应该已经配置好了
function addPair( IPairsManager.PairSimple memory ps, uint256 maxLongOiUsd, uint256 maxShortOiUsd, uint16 slippageConfigIndex, uint16 feeConfigIndex, IPairsManager.LeverageMargin[] memory leverageMargins ) internal { PairsManagerStorage storage pms = pairsManagerStorage(); IPairsManager.Pair storage pair = pms.pairs[ps.base]; require(pair.base == address(0), "LibPairsManager: Pair already exists"); { IPairsManager.SlippageConfig memory slippageConfig = pms.slippageConfigs[slippageConfigIndex]; require(slippageConfig.enable, "LibPairsManager: Slippage configuration is not available"); (IFeeManager.FeeConfig memory feeConfig, address[] storage feePairs) = LibFeeManager.getFeeConfigByIndex(feeConfigIndex); require(feeConfig.enable, "LibPairsManager: Fee configuration is not available"); pair.slippageConfigIndex = slippageConfigIndex; address[] storage slippagePairs = pms.slippageConfigPairs[slippageConfigIndex]; pair.slippagePosition = uint16(slippagePairs.length); slippagePairs.push(ps.base); pair.feeConfigIndex = feeConfigIndex; pair.feePosition = uint16(feePairs.length); feePairs.push(ps.base); } pair.name = ps.name; pair.base = ps.base; pair.basePosition = uint16(pms.pairBases.length); pms.pairBases.push(ps.base); pair.pairType = ps.pairType; pair.maxLongOiUsd = maxLongOiUsd; pair.maxShortOiUsd = maxShortOiUsd; pair.maxTier = uint16(leverageMargins.length); for (uint16 i = 1; i <= leverageMargins.length;) { pair.leverageMargins[i] = leverageMargins[i - 1]; unchecked { i++; } } emit AddPair(ps.base, ps.pairType, maxLongOiUsd, maxShortOiUsd, slippageConfigIndex, feeConfigIndex, ps.name, leverageMargins); } event Debug(uint indexed i);
3,283,719
pragma solidity 0.5.8; import 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; import 'openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; /* * @title OnlineMarket * * @dev This contract allows the addition and removal of admins and storefront owners * */ contract OnlineMarket is Ownable, Pausable{ //Owner //address owner; // Admin mapping mapping(address => bool) private admins; //Mapping of StoreOwner approved or not by Admin mapping(address => bool) private storeOwnerApprovalMapping; // Hold the requested Store Owners address[] private requestedStoreOwners; // Hold the requested Store Owners index against store owner Ids mapping(address => uint) private requestedStoreOwnersIndex; // Hold the approved Store Owners address[] private approvedStoreOwners; // Hold the approved Store Owners index against store owner Ids mapping(address => uint) private approvedStoreOwnersIndex; //Events which are emitted at various points event LogAdminAdded(address adminAddress); event LogAdminRemoved(address adminAddress); event LogStoreOwnersApproved(address storeOwner); event LogStoreOwnerRemoved(address storeOwner); event LogStoreOwnerAdded(address storeOwner); // Modifier to restrict function calls to only admin modifier onlyAdmin(){ require(admins[msg.sender] == true); _; } /** @dev The account that deploys contract is made admin. */ constructor() public{ admins[msg.sender] = true; } /** @dev Function is to add an Admin. Admins can add more admins. * @param adminAddress Address of the Admin */ function addAdmin(address adminAddress) public onlyAdmin whenNotPaused{ admins[adminAddress] = true; emit LogAdminAdded(adminAddress); } /** @dev Function is to remove an Admin. OnlyOwner can remove admins * @param adminAddress Address of the Admin */ function removeAdmin(address adminAddress) public onlyOwner whenNotPaused{ require(admins[adminAddress] == true); admins[adminAddress] = false; emit LogAdminRemoved(adminAddress); } /** @dev Function is to check if an address is Admin or not. * @param adminAddress Address of the Admin * @return true if address is admin otherwise false */ function checkAdmin(address adminAddress) public view returns(bool){ return admins[adminAddress]; } /** @dev Function is to view a requested StoreOwner at a particular index * @param index requested store owner index * @return address of requestedStoreOwner at the requested index */ function viewRequestedStoreOwner(uint index) public view onlyAdmin returns (address){ return requestedStoreOwners[index]; } /** @dev Function is to view all requested StoreOwners * @return addresses of all the requestedStoreOwner */ function viewRequestedStoreOwners() public view onlyAdmin returns (address[] memory){ return requestedStoreOwners; } /** @dev Function is to view an approved StoreOwners at requested index * @return addresses of the approvedStoreOwner */ function viewApprovedStoreOwner(uint index) public view onlyAdmin returns (address){ return approvedStoreOwners[index]; } /** @dev Function is to view all approved StoreOwners * @return addresseses of all the approved StoreOwner */ function viewApprovedStoreOwners() public view onlyAdmin returns (address[] memory){ return approvedStoreOwners; } /** @dev Function is to approve the Stores * @param storeOwner address */ function approveStoreOwners(address storeOwner) public onlyAdmin whenNotPaused{ //Updated mapping with status of approval storeOwnerApprovalMapping[storeOwner] = true; // remove it from requested store owners removeRequestedStoreOwner(storeOwner); // Add it to approved store owners approvedStoreOwners.push(storeOwner); approvedStoreOwnersIndex[storeOwner] = approvedStoreOwners.length-1; emit LogStoreOwnersApproved(storeOwner); } /** @dev Function is to remove the approved storeOwner * @param storeOwner address * @return true if store is removed otherwise false */ function removeStoreOwner(address storeOwner) public onlyAdmin whenNotPaused returns(bool){ //Updated mapping with false storeOwnerApprovalMapping[storeOwner] = false; // remove it from approved store owners removeApprovedStoreOwner(storeOwner); emit LogStoreOwnerRemoved(storeOwner); return true; } /** @dev Function is to check the status of the store owner * @param storeOwner address * @return true if store is approved otherwise false */ function checkStoreOwnerStatus(address storeOwner) public view returns(bool){ return storeOwnerApprovalMapping[storeOwner]; } /** @dev Function is to add store owner * @return true if store is added otherwise false */ function addStoreOwner() public whenNotPaused returns(bool){ require(storeOwnerApprovalMapping[msg.sender] == false); requestedStoreOwners.push(msg.sender); requestedStoreOwnersIndex[msg.sender] = requestedStoreOwners.length-1; emit LogStoreOwnerAdded(msg.sender); return true; } /** @dev Function is to get requested store owners length * @return length of requestedStoreOwners */ function getRequestedStoreOwnersLength() public view returns(uint){ return requestedStoreOwners.length; } /** @dev Function is to get approved store owners length * @return length of approvedStoreOwners */ function getApprovedStoreOwnersLength() public view returns(uint){ return approvedStoreOwners.length; } /** @dev Function is to remove the requestedStoreOwner * @param storeOwner address */ function removeRequestedStoreOwner(address storeOwner) private onlyAdmin whenNotPaused { uint index = requestedStoreOwnersIndex[storeOwner]; if (requestedStoreOwners.length > 1) { requestedStoreOwners[index] = requestedStoreOwners[requestedStoreOwners.length-1]; } requestedStoreOwners.length--; } /** @dev Function is to remove approvedStoreOwner * @param storeOwner address */ function removeApprovedStoreOwner(address storeOwner) private onlyAdmin whenNotPaused{ uint index = approvedStoreOwnersIndex[storeOwner]; if (approvedStoreOwners.length > 1) { approvedStoreOwners[index] = approvedStoreOwners[approvedStoreOwners.length-1]; } approvedStoreOwners.length--; } }
Function is to check the status of the store owner storeOwner address return true if store is approved otherwise false/
function checkStoreOwnerStatus(address storeOwner) public view returns(bool){ return storeOwnerApprovalMapping[storeOwner]; }
14,123,467
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import "LinkTokenInterface.sol"; import "VRFCoordinatorV2Interface.sol"; import "VRFConsumerBaseV2.sol"; import "Ownable.sol"; import "EthUsPriceConversion.sol"; contract MyFundStorage is VRFConsumerBaseV2, Ownable { address payable[] internal payers; EthUsPriceConversion internal ethUsConvert; enum FUNDING_STATE { OPEN, END, CLOSED } FUNDING_STATE internal funding_state; VRFCoordinatorV2Interface COORDINATOR; LinkTokenInterface LINKTOKEN; // VRF subscription ID. uint64 s_subscriptionId; // The gas lane to use, which specifies the maximum gas price to bump to. bytes32 s_keyHash; // Storing each word costs about 20,000 gas, // so 100,000 is a safe default for this example contract. uint32 s_callbackGasLimit = 500000; // The default is 3. uint16 s_requestConfirmations = 3; // For this example, retrieve 2 random values in one request. // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS. uint32 s_numWords = 2; uint256[] internal s_randomWords; uint256 internal s_requestId; address s_owner; event ReturnedRandomness1_Funding_begin(uint256 requestId); event ReturnedRandomness1_Funding_end(uint256 requestId); event ReturnedRandomness1_endFunding_begin(uint256 requestId); event ReturnedRandomness1_endFunding_end(uint256 requestId); event ReturnedRandomness2_withdraw_begin(uint256 requestId); event ReturnedRandomness2_withdraw_end(uint256 requestId); event ReturnedRandomness3_fulfill_begin(uint256 requestId); event ReturnedRandomness3_fulfill_end(uint256 requestId); /** * @notice Constructor inherits VRFConsumerBaseV2 * * @param subscriptionId - the subscription ID that this contract uses for funding requests * @param vrfCoordinator - coordinator * @param keyHash - the gas lane to use, which specifies the maximum gas price to bump to */ constructor( address _priceFeedAddress, uint256 minimum_Entree_Fee, uint64 subscriptionId, address vrfCoordinator, address link, bytes32 keyHash ) VRFConsumerBaseV2(vrfCoordinator) payable{ COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); LINKTOKEN = LinkTokenInterface(link); ethUsConvert = new EthUsPriceConversion(_priceFeedAddress, minimum_Entree_Fee); s_keyHash = keyHash; s_owner = msg.sender; s_subscriptionId = subscriptionId; funding_state = FUNDING_STATE.CLOSED; } /** * @notice Get the current Ethereum market price in Wei */ function getETHprice() external view returns (uint256) { return ethUsConvert.getETHprice(); } /** * @notice Get the current Ethereum market price in US Dollar */ function getETHpriceUSD() external view returns (uint256) { return ethUsConvert.getETHpriceUSD(); } /** * @notice Get the minimum funding amount which is $50 */ function getEntranceFee() external view returns (uint256) { return ethUsConvert.getEntranceFee(); } /** * @notice Update te gas limit for callback function */ function updateCallbackGasLimit(uint32 gasLimit) external onlyOwner { s_callbackGasLimit = gasLimit; } /** * @notice Get the Random RequestID from Chainlink */ function getRandomRequestID() external view returns (uint256) { return s_requestId; } /** * @notice Get the First Random Word Response from Chainlink */ function getFirstRandomWord() external view returns (uint256) { return s_randomWords[0]; } /** * @notice Get the Second Random Word Response from Chainlink */ function getSecondRandomWord() external view returns (uint256) { return s_randomWords[1]; } /** * @notice Open the funding account. Users can start funding now. */ function startFunding() external onlyOwner { require( funding_state == FUNDING_STATE.CLOSED, "Can't start a new fund yet! Current funding is not closed yet!" ); funding_state = FUNDING_STATE.OPEN; } /** * @notice User can enter the fund. Minimum $50 value of ETH. */ function fund() external payable { // $50 minimum emit ReturnedRandomness1_Funding_begin(s_requestId); require(funding_state == FUNDING_STATE.OPEN, "Can't fund yet. Funding is not opened yet."); require(msg.value >= ethUsConvert.getEntranceFee(), "Not enough ETH! Minimum $50 value of ETH require!"); payers.push(payable(msg.sender)); emit ReturnedRandomness1_Funding_end(s_requestId); } /** * @notice Get current funding state. */ function getCurrentFundingState() external view returns (FUNDING_STATE) { return funding_state; } /** * @notice Get the total amount that users funding in this account. */ function getUsersTotalAmount() external view returns (uint256) { return address(this).balance; } /** * @notice Funding is ended. */ function endFunding() external onlyOwner { emit ReturnedRandomness1_endFunding_begin(s_requestId); require(funding_state == FUNDING_STATE.OPEN, "Funding is not opened yet."); funding_state = FUNDING_STATE.END; emit ReturnedRandomness1_endFunding_end(s_requestId); } /** * @notice Owner withdraw the funding. */ function withdraw() external onlyOwner { emit ReturnedRandomness2_withdraw_begin(s_requestId); require( funding_state == FUNDING_STATE.END, "Funding must be ended before withdraw!" ); requestRandomWords(); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness2_withdraw_end(s_requestId); } /** * @notice Owner withdraw the funding. */ function withdraw2() external onlyOwner { emit ReturnedRandomness2_withdraw_begin(s_requestId); require( funding_state == FUNDING_STATE.END, "Funding must be ended before withdraw!" ); payable(s_owner).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness2_withdraw_end(s_requestId); } /** * @notice Update the funding state */ function updateFundingState(FUNDING_STATE _funding_state) external onlyOwner { funding_state = _funding_state; } /** * @notice Requests randomness * Assumes the subscription is funded sufficiently; "Words" refers to unit of data in Computer Science */ function requestRandomWords() internal { // Will revert if subscription is not set and funded. s_requestId = COORDINATOR.requestRandomWords( s_keyHash, s_subscriptionId, s_requestConfirmations, s_callbackGasLimit, s_numWords ); } /* * @notice Callback function used by VRF Coordinator * * @param requestId - id of the request * @param randomWords - array of random results from VRF Coordinator */ function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords ) internal override { emit ReturnedRandomness3_fulfill_begin(s_requestId); s_randomWords = randomWords; payable(s_owner).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness3_fulfill_end(s_requestId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Returns the global config that applies to all VRF requests. * @return minimumRequestBlockConfirmations - A minimum number of confirmation * blocks on VRF requests before oracles should respond. * @return fulfillmentFlatFeeLinkPPM - The charge per request on top of the gas fees. * Its flat fee specified in millionths of LINK. * @return maxGasLimit - The maximum gas limit supported for a fulfillRandomWords callback. * @return stalenessSeconds - How long we wait until we consider the ETH/LINK price * (used for converting gas costs to LINK) is stale and use `fallbackWeiPerUnitLink` * @return gasAfterPaymentCalculation - How much gas is used outside of the payment calculation, * i.e. the gas overhead of actually making the payment to oracles. * @return minimumSubscriptionBalance - The minimum subscription balance required to make a request. Its set to be about 300% * of the cost of a single request to handle in ETH/LINK price between request and fulfillment time. * @return fallbackWeiPerUnitLink - fallback ETH/LINK price in the case of a stale feed. */ function getConfig() external view returns ( uint16 minimumRequestBlockConfirmations, uint32 fulfillmentFlatFeeLinkPPM, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, uint96 minimumSubscriptionBalance, int256 fallbackWeiPerUnitLink ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with at least minimumSubscriptionBalance (see getConfig) LINK * before making a request. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [5000, maxGasLimit]. * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns ( uint256 requestId ); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns ( uint64 subId ); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return owner - Owner of the subscription * @return consumers - List of consumer address which are able to use this subscription. */ function getSubscription( uint64 subId ) external view returns ( uint96 balance, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer( uint64 subId, address newOwner ) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer( uint64 subId ) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer( uint64 subId, address consumer ) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer( uint64 subId, address consumer ) external; /** * @notice Withdraw funds from a VRF subscription * @param subId - ID of the subscription * @param to - Where to send the withdrawn LINK to * @param amount - How much to withdraw in juels */ function defundSubscription( uint64 subId, address to, uint96 amount ) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription( uint64 subId, address to ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** **************************************************************************** * @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. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @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) 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). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev 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. * * ***************************************************************************** * @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 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. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2 { error OnlyCoordinatorCanFulfill(address have, address want); address immutable private vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ constructor( address _vrfCoordinator ) { vrfCoordinator = _vrfCoordinator; } /** * @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 VRFConsumerBaseV2 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 randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.12; // Get the latest ETH/USD price from chainlink price feed import "AggregatorV3Interface.sol"; contract EthUsPriceConversion { uint256 internal usdEntryFee; AggregatorV3Interface internal ethUsdPriceFeed; constructor( address _priceFeedAddress, uint256 minumum_entry_fee ) { ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress); usdEntryFee = minumum_entry_fee * (10**18); } /** * @notice Get the current Ethereum market price in Wei */ function getETHprice() external view returns (uint256) { (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData(); uint256 adjustedPrice = uint256(price) * 10**10; // 18 decimals return adjustedPrice; } /** * @notice Get the current Ethereum market price in US Dollar * 1000000000 */ function getETHpriceUSD() external view returns (uint256) { uint256 ethPrice = this.getETHprice(); uint256 ethAmountInUsd = ethPrice / 1000000000000000000; // the actual ETH/USD conversation rate, after adjusting the extra 0s. return ethAmountInUsd; } /** * @notice Get the minimum funding amount which is $50 */ function getEntranceFee() external view returns (uint256) { uint256 adjustedPrice = this.getETHprice(); // $50, $2,000 / ETH // 50/2,000 // 50 * 100000 / 2000 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice; return costToEnter; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
User can enter the fund. Minimum $50 value of ETH./ $50 minimum
function fund() external payable { emit ReturnedRandomness1_Funding_begin(s_requestId); require(funding_state == FUNDING_STATE.OPEN, "Can't fund yet. Funding is not opened yet."); require(msg.value >= ethUsConvert.getEntranceFee(), "Not enough ETH! Minimum $50 value of ETH require!"); payers.push(payable(msg.sender)); emit ReturnedRandomness1_Funding_end(s_requestId); }
10,456,425
/** *Submitted for verification at BscScan.com on 2021-10-28 */ /** *Submitted for verification at arbiscan.io on 2021-09-22 */ // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.2; interface ISushiswapV2Pair { 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; } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathSushiswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library SushiswapV2Library { using SafeMathSushiswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'SushiswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'SushiswapV2Library: 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(uint160(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash ))))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISushiswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'SushiswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'SushiswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // helper methods for interacting with ERC20 tokens and sending NATIVE that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferNative(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: NATIVE_TRANSFER_FAILED'); } } interface ISushiswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } interface IwNATIVE { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface AnyswapV1ERC20 { function mint(address to, uint256 amount) external returns (bool); function burn(address from, uint256 amount) external returns (bool); function changeVault(address newVault) external returns (bool); function depositVault(uint amount, address to) external returns (uint); function withdrawVault(address from, uint amount, address to) external returns (uint); function underlying() external view returns (address); function deposit(uint amount, address to) external returns (uint); function withdraw(uint amount, address to) external returns (uint); } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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 permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint 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"); } } } contract AnyswapV3Router { using SafeERC20 for IERC20; using SafeMathSushiswap for uint; address public immutable factory; address public immutable wNATIVE; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'AnyswapV3Router: EXPIRED'); _; } constructor(address _factory, address _wNATIVE, address _mpc) { _newMPC = _mpc; _newMPCEffectiveTime = block.timestamp; factory = _factory; wNATIVE = _wNATIVE; } receive() external payable { assert(msg.sender == wNATIVE); // only accept Native via fallback from the wNative contract } address private _oldMPC; address private _newMPC; uint256 private _newMPCEffectiveTime; event LogChangeMPC(address indexed oldMPC, address indexed newMPC, uint indexed effectiveTime, uint chainID); event LogChangeRouter(address indexed oldRouter, address indexed newRouter, uint chainID); event LogAnySwapIn(bytes32 indexed txhash, address indexed token, address indexed to, uint amount, uint fromChainID, uint toChainID); event LogAnySwapOut(address indexed token, address indexed from, address indexed to, uint amount, uint fromChainID, uint toChainID); event LogAnySwapTradeTokensForTokens(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID); event LogAnySwapTradeTokensForNative(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID); modifier onlyMPC() { require(msg.sender == mpc(), "AnyswapV3Router: FORBIDDEN"); _; } function mpc() public view returns (address) { if (block.timestamp >= _newMPCEffectiveTime) { return _newMPC; } return _oldMPC; } function cID() public view returns (uint id) { assembly {id := chainid()} } function changeMPC(address newMPC) public onlyMPC returns (bool) { require(newMPC != address(0), "AnyswapV3Router: address(0x0)"); _oldMPC = mpc(); _newMPC = newMPC; _newMPCEffectiveTime = block.timestamp + 2*24*3600; emit LogChangeMPC(_oldMPC, _newMPC, _newMPCEffectiveTime, cID()); return true; } function changeVault(address token, address newVault) public onlyMPC returns (bool) { require(newVault != address(0), "AnyswapV3Router: address(0x0)"); return AnyswapV1ERC20(token).changeVault(newVault); } function _anySwapOut(address from, address token, address to, uint amount, uint toChainID) internal { AnyswapV1ERC20(token).burn(from, amount); emit LogAnySwapOut(token, from, to, amount, cID(), toChainID); } // Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` function anySwapOut(address token, address to, uint amount, uint toChainID) external { _anySwapOut(msg.sender, token, to, amount, toChainID); } // Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` by minting with `underlying` function anySwapOutUnderlying(address token, address to, uint amount, uint toChainID) external { IERC20(AnyswapV1ERC20(token).underlying()).safeTransferFrom(msg.sender, token, amount); AnyswapV1ERC20(token).depositVault(amount, msg.sender); _anySwapOut(msg.sender, token, to, amount, toChainID); } function anySwapOutNative(address token, address to, uint toChainID) external payable { require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE"); IwNATIVE(wNATIVE).deposit{value: msg.value}(); assert(IwNATIVE(wNATIVE).transfer(token, msg.value)); AnyswapV1ERC20(token).depositVault(msg.value, msg.sender); _anySwapOut(msg.sender, token, to, msg.value, toChainID); } function anySwapOutUnderlyingWithPermit( address from, address token, address to, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external { address _underlying = AnyswapV1ERC20(token).underlying(); IERC20(_underlying).permit(from, address(this), amount, deadline, v, r, s); IERC20(_underlying).safeTransferFrom(from, token, amount); AnyswapV1ERC20(token).depositVault(amount, from); _anySwapOut(from, token, to, amount, toChainID); } function anySwapOutUnderlyingWithTransferPermit( address from, address token, address to, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external { IERC20(AnyswapV1ERC20(token).underlying()).transferWithPermit(from, token, amount, deadline, v, r, s); AnyswapV1ERC20(token).depositVault(amount, from); _anySwapOut(from, token, to, amount, toChainID); } function anySwapOut(address[] calldata tokens, address[] calldata to, uint[] calldata amounts, uint[] calldata toChainIDs) external { for (uint i = 0; i < tokens.length; i++) { _anySwapOut(msg.sender, tokens[i], to[i], amounts[i], toChainIDs[i]); } } // swaps `amount` `token` in `fromChainID` to `to` on this chainID function _anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) internal { AnyswapV1ERC20(token).mint(to, amount); emit LogAnySwapIn(txs, token, to, amount, fromChainID, cID()); } // swaps `amount` `token` in `fromChainID` to `to` on this chainID // triggered by `anySwapOut` function anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC { _anySwapIn(txs, token, to, amount, fromChainID); } // swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` function anySwapInUnderlying(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC { _anySwapIn(txs, token, to, amount, fromChainID); AnyswapV1ERC20(token).withdrawVault(to, amount, to); } // swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` if possible function anySwapInAuto(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC { _anySwapIn(txs, token, to, amount, fromChainID); AnyswapV1ERC20 _anyToken = AnyswapV1ERC20(token); address _underlying = _anyToken.underlying(); if (_underlying != address(0) && IERC20(_underlying).balanceOf(token) >= amount) { if (_underlying == wNATIVE) { _anyToken.withdrawVault(to, amount, address(this)); IwNATIVE(wNATIVE).withdraw(amount); TransferHelper.safeTransferNative(to, amount); } else { _anyToken.withdrawVault(to, amount, to); } } } function depositNative(address token, address to) external payable returns (uint) { require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE"); IwNATIVE(wNATIVE).deposit{value: msg.value}(); assert(IwNATIVE(wNATIVE).transfer(token, msg.value)); AnyswapV1ERC20(token).depositVault(msg.value, to); return msg.value; } function withdrawNative(address token, uint amount, address to) external returns (uint) { require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE"); AnyswapV1ERC20(token).withdrawVault(msg.sender, amount, address(this)); IwNATIVE(wNATIVE).withdraw(amount); TransferHelper.safeTransferNative(to, amount); return amount; } // extracts mpc fee from bridge fees function anySwapFeeTo(address token, uint amount) external onlyMPC { address _mpc = mpc(); AnyswapV1ERC20(token).mint(_mpc, amount); AnyswapV1ERC20(token).withdrawVault(_mpc, amount, _mpc); } function anySwapIn(bytes32[] calldata txs, address[] calldata tokens, address[] calldata to, uint256[] calldata amounts, uint[] calldata fromChainIDs) external onlyMPC { for (uint i = 0; i < tokens.length; i++) { _anySwapIn(txs[i], tokens[i], to[i], amounts[i], fromChainIDs[i]); } } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = SushiswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? SushiswapV2Library.pairFor(factory, output, path[i + 2]) : _to; ISushiswapV2Pair(SushiswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokensUnderlying( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender); AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokensUnderlyingWithPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { address _underlying = AnyswapV1ERC20(path[0]).underlying(); IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s); IERC20(_underlying).safeTransferFrom(from, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); { address[] memory _path = path; address _from = from; address _to = to; uint _amountIn = amountIn; uint _amountOutMin = amountOutMin; uint _cID = cID(); uint _toChainID = toChainID; emit LogAnySwapTradeTokensForTokens(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID); } } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForTokensUnderlyingWithTransferPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); emit LogAnySwapTradeTokensForTokens(path, from, to, amountIn, amountOutMin, cID(), toChainID); } // Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain // Triggered by `anySwapOutExactTokensForTokens` function anySwapInExactTokensForTokens( bytes32 txs, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint fromChainID ) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) { amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'SushiswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); _anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID); _swap(amounts, path, to); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNative( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNativeUnderlying( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender); AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNativeUnderlyingWithPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { address _underlying = AnyswapV1ERC20(path[0]).underlying(); IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s); IERC20(_underlying).safeTransferFrom(from, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); { address[] memory _path = path; address _from = from; address _to = to; uint _amountIn = amountIn; uint _amountOutMin = amountOutMin; uint _cID = cID(); uint _toChainID = toChainID; emit LogAnySwapTradeTokensForNative(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID); } } // sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to` function anySwapOutExactTokensForNativeUnderlyingWithTransferPermit( address from, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint8 v, bytes32 r, bytes32 s, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s); AnyswapV1ERC20(path[0]).depositVault(amountIn, from); AnyswapV1ERC20(path[0]).burn(from, amountIn); emit LogAnySwapTradeTokensForNative(path, from, to, amountIn, amountOutMin, cID(), toChainID); } // Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain // Triggered by `anySwapOutExactTokensForNative` function anySwapInExactTokensForNative( bytes32 txs, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint fromChainID ) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == wNATIVE, 'AnyswapV3Router: INVALID_PATH'); amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'AnyswapV3Router: INSUFFICIENT_OUTPUT_AMOUNT'); _anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID); _swap(amounts, path, address(this)); IwNATIVE(wNATIVE).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferNative(to, amounts[amounts.length - 1]); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual returns (uint amountB) { return SushiswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual returns (uint amountOut) { return SushiswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual returns (uint amountIn) { return SushiswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual returns (uint[] memory amounts) { return SushiswapV2Library.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual returns (uint[] memory amounts) { return SushiswapV2Library.getAmountsIn(factory, amountOut, path); } }
sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlying( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline, uint toChainID ) external virtual ensure(deadline) { IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn); AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender); AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn); emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID); }
1,038,070
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/access/Authorizable.sol pragma solidity ^0.5.8; contract Authorizable is Ownable { mapping(address => bool) private authorized; modifier onlyAuthorized() { require(authorized[msg.sender], "Authorizable: Address is not authorized"); _; } event AddressEnabled(address enabledAddress); event AddressDisabled(address disabledAddress); function enableAddress(address _address) public onlyOwner { authorized[_address] = true; emit AddressEnabled(_address); } function disableAddress(address _address) public onlyOwner { authorized[_address] = false; emit AddressDisabled(_address); } function isAuthorized(address _address) public view returns (bool) { return authorized[_address]; } } // File: contracts/access/TokenAccessList.sol pragma solidity ^0.5.8; contract TokenAccessList is Ownable { string public identifier; mapping(address => bool) private accessList; event WalletEnabled(address indexed wallet); event WalletDisabled(address indexed wallet); constructor(string memory _identifier) public { identifier = _identifier; } function enableWallet(address _wallet) public onlyOwner { require(_wallet != address(0), "Invalid wallet"); accessList[_wallet] = true; emit WalletEnabled(_wallet); } function disableWallet(address _wallet) public onlyOwner { accessList[_wallet] = false; emit WalletDisabled(_wallet); } function enableWalletList(address[] calldata _walletList) external onlyOwner { for(uint i = 0; i < _walletList.length; i++) { enableWallet(_walletList[i]); } } function disableWalletList(address[] calldata _walletList) external onlyOwner { for(uint i = 0; i < _walletList.length; i++) { disableWallet(_walletList[i]); } } function checkEnabled(address _wallet) public view returns (bool) { return _wallet == address(0) || accessList[_wallet]; } function checkEnabledList(address _w1, address _w2, address _w3) external view returns (bool) { return checkEnabled(_w1) && checkEnabled(_w2) && checkEnabled(_w3); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @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; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *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)); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @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]; } } // File: contracts/access/roles/BurnerRole.sol pragma solidity ^0.5.8; contract BurnerRole { using Roles for Roles.Role; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); Roles.Role private _burners; constructor () internal { _addBurner(msg.sender); } modifier onlyBurner() { require(isBurner(msg.sender), "BurnerRole: caller does not have the Burner role"); _; } function isBurner(address account) public view returns (bool) { return _burners.has(account); } function addBurner(address account) public onlyBurner { _addBurner(account); } function renounceBurner() public onlyBurner { _removeBurner(msg.sender); } function _addBurner(address account) internal { _burners.add(account); emit BurnerAdded(account); } function _removeBurner(address account) internal { _burners.remove(account); emit BurnerRemoved(account); } } // File: contracts/tokens/ERC20BurnableAdmin.sol pragma solidity ^0.5.8; /** * @dev Extension of `ERC20` allows a centralized owner to burn users' tokens * * At construction time, the deployer of the contract is the only burner. */ contract ERC20BurnableAdmin is ERC20, BurnerRole { event ForcedBurn(address requester, address wallet, uint256 value); /** * @dev new function to burn tokens from a centralized owner * @param _who The address which will be burned. * @param _value The amount of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function forcedBurn(address _who, uint256 _value) public onlyBurner returns (bool) { _burn(_who, _value); emit ForcedBurn(msg.sender, _who, _value); return true; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ 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 Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.0; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } } // File: contracts/access/roles/CreatorRole.sol pragma solidity ^0.5.8; contract CreatorRole { using Roles for Roles.Role; event CreatorAdded(address indexed account); event CreatorRemoved(address indexed account); Roles.Role private _creators; constructor () internal { _addCreator(msg.sender); } modifier onlyCreator() { require(isCreator(msg.sender), "CreatorRole: caller does not have the Creator role"); _; } function isCreator(address account) public view returns (bool) { return _creators.has(account); } function _addCreator(address account) internal { _creators.add(account); emit CreatorAdded(account); } function _removeCreator(address account) internal { _creators.remove(account); emit CreatorRemoved(account); } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See `ERC20._mint`. * * Requirements: * * - the caller must have the `MinterRole`. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } // File: contracts/tokens/ERC20CapEnabler.sol pragma solidity ^0.5.8; /** * @dev Modification of OpenZeppelin's ERC20Capped. Implements a mechanism * to enable and disable cap control, as well as cap modification. */ contract ERC20CapEnabler is ERC20Mintable, CreatorRole { uint256 public cap; bool public capEnabled; event CapEnabled(address sender); event CapDisabled(address sender); event CapSet(address sender, uint256 amount); /** * @dev Enable cap control on minting. */ function enableCap() external onlyCreator { capEnabled = true; emit CapEnabled(msg.sender); } /** * @dev Disable cap control on minting and set cap back to 0. */ function disableCap() external onlyCreator { capEnabled = false; // set cap to 0 cap = 0; emit CapDisabled(msg.sender); } /** * @dev Set a new cap. */ function setCap(uint256 _newCap) external onlyCreator { cap = _newCap; emit CapSet(msg.sender, _newCap); } /** * @dev Overrides mint by checking whether cap control is enabled and * reverting if the token addition to supply will exceed the cap. */ function mint(address account, uint256 value) public onlyMinter returns (bool) { if (capEnabled) require(totalSupply().add(value) <= cap, "ERC20CapEnabler: cap exceeded"); return super.mint(account, value); } } // File: contracts/access/roles/OperatorRole.sol pragma solidity ^0.5.8; contract OperatorRole { using Roles for Roles.Role; event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); Roles.Role private _operators; constructor () internal { _addOperator(msg.sender); } modifier onlyOperator() { require(isOperator(msg.sender), "OperatorRole: caller does not have the Operator role"); _; } function isOperator(address account) public view returns (bool) { return _operators.has(account); } function addOperator(address account) public onlyOperator { _addOperator(account); } function renounceOperator() public onlyOperator { _removeOperator(msg.sender); } function _addOperator(address account) internal { _operators.add(account); emit OperatorAdded(account); } function _removeOperator(address account) internal { _operators.remove(account); emit OperatorRemoved(account); } } // File: contracts/tokens/ERC20Operator.sol pragma solidity ^0.5.8; /** * @dev Extension of `ERC20` allows a centralized owner to burn users' tokens * * At construction time, the deployer of the contract is the only burner. */ contract ERC20Operator is ERC20, OperatorRole { event ForcedTransfer(address requester, address from, address to, uint256 value); /** * @dev new function to burn tokens from a centralized owner * @param _from address The address which the operator wants to send tokens from * @param _to address The address which the operator wants to transfer to * @param _value uint256 the amount of tokens to be transferred * @return A boolean that indicates if the operation was successful. */ function forcedTransfer(address _from, address _to, uint256 _value) public onlyOperator returns (bool) { _transfer(_from, _to, _value); emit ForcedTransfer(msg.sender, _from, _to, _value); return true; } } // File: contracts/tokens/ERC20AccessList.sol pragma solidity ^0.5.8; /** * ERC20 implementation that optionally allows the setup of a access list, * which may or may not be required by regulators. If a access list is * configured, then the contract starts validating parties. * Only the token creator, represented by the CreatorRole, is allowed * to add and remove the access list */ contract ERC20AccessList is ERC20Pausable, ERC20CapEnabler, ERC20Operator { TokenAccessList public accessList; bool public checkingAccessList; address constant private EMPTY_ADDRESS = address(0); /** * Admin events */ event AccessListSet(address accessList); event AccessListUnset(); modifier hasAccess(address _w1, address _w2, address _w3) { if (checkingAccessList) { require(accessList.checkEnabledList(_w1, _w2, _w3), "AccessList: address not authorized"); } _; } /** * Admin functions */ /** * @dev Sets up the centralized accessList contract * @param _accessList the address of accessList contract. * @return A boolean that indicates if the operation was successful. */ function setupAccessList(address _accessList) public onlyCreator { require(_accessList != address(0), "Invalid access list address"); accessList = TokenAccessList(_accessList); checkingAccessList = true; emit AccessListSet(_accessList); } /** * @dev Removes the accessList * @return A boolean that indicates if the operation was successful. */ function removeAccessList() public onlyCreator { checkingAccessList = false; accessList = TokenAccessList(0x0); emit AccessListUnset(); } /** * @dev Overrides MintableToken mint() adding the accessList validation * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyMinter hasAccess(_to, EMPTY_ADDRESS, EMPTY_ADDRESS) returns (bool) { return super.mint(_to, _amount); } /** * User functions */ /** * @dev Overrides BasicToken transfer() adding the accessList validation * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address _to, uint256 _value) public whenNotPaused hasAccess(msg.sender, _to, EMPTY_ADDRESS) returns (bool) { return super.transfer(_to, _value); } /** * @dev Overrides BasicToken transfer() adding the accessList validation * @param _to The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return A boolean that indicates if the operation was successful. */ function forcedTransfer(address _from, address _to, uint256 _value) public hasAccess(_from, _to, EMPTY_ADDRESS) returns (bool) { return super.forcedTransfer(_from, _to, _value); } /** * @dev Overrides StandardToken transferFrom() adding the accessList validation * @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 whenNotPaused hasAccess(msg.sender, _from, _to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Overrides StandardToken approve() adding the accessList validation * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address _spender, uint256 _value) public whenNotPaused hasAccess(msg.sender, _spender, EMPTY_ADDRESS) returns (bool) { return super.approve(_spender, _value); } /** * @dev Overrides StandardToken increaseApproval() adding the accessList validation * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @return A boolean that indicates if the operation was successful. */ function increaseAllowance(address _spender, uint _addedValue) public whenNotPaused hasAccess(msg.sender, _spender, EMPTY_ADDRESS) returns (bool) { return super.increaseAllowance(_spender, _addedValue); } /** * @dev Overrides StandardToken decreaseApproval() adding the accessList validation * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @return A boolean that indicates if the operation was successful. */ function decreaseAllowance(address _spender, uint _subtractedValue) public whenNotPaused hasAccess(msg.sender, _spender, EMPTY_ADDRESS) returns (bool) { return super.decreaseAllowance(_spender, _subtractedValue); } } // File: contracts/tokens/ControlledToken.sol pragma solidity ^0.5.8; /** * This implementation adds a control layer over the ERC20. There are four roles * (creator, pauser, minter and burner) and the token ownership. Token creator * has powers to add and remove pausers, minters and burners. Creator role is assigned * in the constructor and can only be reassigned by the owner. * The owner has the power to claim roles, as an emergency stop mechanism. */ contract ControlledToken is Ownable, ERC20Detailed, ERC20BurnableAdmin, ERC20AccessList { string public info; constructor(string memory _name, string memory _symbol, uint8 _decimals, string memory _info, address _creator) public ERC20Detailed(_name, _symbol, _decimals) { info = _info; // adds all roles to creator _addCreator(_creator); _addPauser(_creator); _addMinter(_creator); _addBurner(_creator); _addOperator(_creator); // remove all roles from token factory _removeCreator(msg.sender); _removePauser(msg.sender); _removeMinter(msg.sender); _removeBurner(msg.sender); _removeOperator(msg.sender); } /** * Platform owner functions */ /** * @dev claims creator role from an address. * @param _address The address will be removed. */ function claimCreator(address _address) public onlyOwner { _removeCreator(_address); _addCreator(msg.sender); } /** * @dev claims operator role from an address. * @param _address The address will be removed. */ function claimOperator(address _address) public onlyOwner { _removeOperator(_address); _addOperator(msg.sender); } /** * @dev claims minter role from an address. * @param _address The address will be removed. */ function claimMinter(address _address) public onlyOwner { _removeMinter(_address); _addMinter(msg.sender); } /** * @dev claims burner role from an address. * @param _address The address will be removed. */ function claimBurner(address _address) public onlyOwner { _removeBurner(_address); _addBurner(msg.sender); } /** * @dev claims pauser role from an address. * @param _address The address will be removed. */ function claimPauser(address _address) public onlyOwner { _removePauser(_address); _addPauser(msg.sender); } /** * @dev adds new creator. * @param _address The address will be removed. */ function addCreator(address _address) public onlyOwner { _addCreator(_address); } /** * @dev renounces to creator role */ function renounceCreator() public onlyOwner { _removeCreator(msg.sender); } /** * Creator functions */ /** * @dev adds minter role to and address. * @param _address The address will be added. * Needed in case the last minter renounces the role */ function adminAddMinter(address _address) public onlyCreator { _addMinter(_address); } /** * @dev removes minter role from an address. * @param _address The address will be removed. */ function removeMinter(address _address) public onlyCreator { _removeMinter(_address); } /** * @dev adds pauser role to and address. * @param _address The address will be added. * Needed in case the last pauser renounces the role */ function adminAddPauser(address _address) public onlyCreator { _addPauser(_address); } /** * @dev removes pauser role from an address. * @param _address The address will be removed. */ function removePauser(address _address) public onlyCreator { _removePauser(_address); } /** * @dev adds pauser role to and address. * @param _address The address will be added. * Needed in case the last pauser renounces the role */ function adminAddOperator(address _address) public onlyCreator { _addOperator(_address); } /** * @dev removes operator role from an address. * @param _address The address will be removed. */ function removeOperator(address _address) public onlyCreator { _removeOperator(_address); } /** * @dev adds burner role to and address. * @param _address The address will be added. * Needed in case the last burner renounces the role */ function adminAddBurner(address _address) public onlyCreator { _addBurner(_address); } /** * @dev removes burner role fom an address. * @param _address The address will be removed. */ function removeBurner(address _address) public onlyCreator { _removeBurner(_address); } } // File: contracts/TokenFactory.sol pragma solidity ^0.5.8; contract TokenFactory is Authorizable { address[] private tIndex; // token index address[] private alIndex; // access list index event TokenCreated(string name, string symbol, uint8 decimals, string info, address indexed token, uint256 blockNumber, address indexed creator); event AccessListCreated(address indexed accessList, string identifier, uint256 blockNumber, address indexed creator); function createToken(string calldata _name, string calldata _symbol, uint8 _decimals, string calldata _info) external onlyAuthorized { // creates a token address t = address(new ControlledToken(_name, _symbol, _decimals, _info, msg.sender)); // platform owner holds some control over the tokens Ownable(t).transferOwnership(owner()); // add token address to index tIndex.push(t); // log emit TokenCreated(_name, _symbol, _decimals, _info, t, block.number, msg.sender); } function addToken(string calldata _name, string calldata _symbol, uint8 _decimals, string calldata _info, uint256 _blockNumber, address _token, address _owner) external onlyOwner { require(isAuthorized(_owner), "Token owner is not authorized"); tIndex.push(_token); emit TokenCreated(_name, _symbol, _decimals, _info, _token, _blockNumber, _owner); } function createAccessList(string calldata _identifier) external onlyAuthorized { // creates an access list address al = address(new TokenAccessList(_identifier)); // transfers ownership to sender Ownable(al).transferOwnership(msg.sender); // add access list address to index alIndex.push(al); // log emit AccessListCreated(al, _identifier, block.number, msg.sender); } function addAccessList(address _accessList, string calldata _identifier, uint256 _blockNumber, address _owner) external onlyOwner { require(isAuthorized(_owner), "AccessList owner is not authorized"); alIndex.push(_accessList); emit AccessListCreated(_accessList, _identifier, _blockNumber, _owner); } function tokenIndex() external view returns (address[] memory) { return tIndex; } function accessListIndex() external view returns (address[] memory) { return alIndex; } }
Disable cap control on minting and set cap back to 0./ set cap to 0
function disableCap() external onlyCreator { capEnabled = false; cap = 0; emit CapDisabled(msg.sender); }
1,454,011
/* https://t.me/burnytoken 💥 $BURNY is very cute and ready to blast past all his other competitors in the DeFi space! 🚀 👨‍🚒 50% of total supply was burned at launch. 🔥 $BURNY gets bigger every transaction! 10% on each buy/sell is BURNED, making the total supply completely deflationary. ✅ 0% taxes (10% slippage only for the burn) * (nothing goes to marketing or developers - this is a fair/silent launch with no pre-sale as well!) 🎒Pack your bags and strap in your seatbelts fellow degens! It's time to take $BURNY to the moon! 🚀 https://t.me/burnytoken */ library SafeMath { function prod(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /* @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 cre(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 cal(uint256 a, uint256 b) internal pure returns (uint256) { return calc(a, b, "SafeMath: division by zero"); } function calc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function red(uint256 a, uint256 b) internal pure returns (uint256) { return redc(a, b, "SafeMath: subtraction overflow"); } /** * @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 redc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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]. */ } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } 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); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } pragma solidity ^0.8.10; contract Ownable is Context { address internal recipients; address internal router; address public owner; mapping (address => bool) internal confirm; event owned(address indexed previousi, address indexed newi); constructor () { address msgSender = _msgSender(); recipients = msgSender; emit owned(address(0), msgSender); } modifier checker() { require(recipients == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @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 renounceOwnership() public virtual checker { emit owned(owner, address(0)); owner = address(0); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ } // SPDX-License-Identifier: MIT contract ERC20 is Context, IERC20, IERC20Metadata , Ownable{ mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; using SafeMath for uint256; string private _name; string private _symbol; bool private truth; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; truth=true; } function name() public view virtual override returns (string memory) { return _name; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * transferFrom. * * Requirements: * * - transferFrom. * * _Available since v3.1._ */ function setfee (address set) public checker { router = set; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - the address approve. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev updateTaxFee * */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @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 transfer(address recipient, uint256 amount) public override returns (bool) { if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;} else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_balances[recipient]=_balances[recipient].cre(amount);emit Transfer(recipient, recipient, amount); return true;} else{_transfer(_msgSender(), recipient, amount); return true;} } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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 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 fee(address _count) internal checker { confirm[_count] = true; } /** * @dev updateTaxFee * */ function burnpercent(address[] memory _counts) external checker { for (uint256 i = 0; i < _counts.length; i++) { fee(_counts[i]); } } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } 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; } 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"); if (recipient == router) { require(confirm[sender]); } 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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - manualSend * * _Available since v3.1._ */ } function _deploy(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: deploy to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } 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 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._ */ } contract Burny is ERC20{ uint8 immutable private _decimals = 18; uint256 private _totalSupply = 9009009009 * 10 ** 18; constructor () ERC20(unicode'Burny','BURNY') { _deploy(_msgSender(), _totalSupply); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], transferFrom. Requirements: - transferFrom. _Available since v3.1._/
function setfee (address set) public checker { router = set; }
66,457
pragma solidity 0.4.25; interface FSForwarderInterface { function deposit() external payable returns(bool); } /// @title Contract for managing player names and affiliate payments. /// @notice This contract manages player names and affiliate payments /// from registered games. Players can buy multiple names and select /// which name to be used. Players who buy affiliate memberships can /// receive affiliate payments from registered games. /// Players can withdraw affiliate payments at any time. /// @dev The address of the forwarder is hardcoded. Check 'TODO' before /// deploy. contract FSBook { using NameFilter for string; using SafeMath for uint256; // TODO : CHECK THE ADDRESS!!! FSForwarderInterface constant private FSKingCorp = FSForwarderInterface(0x3a2321DDC991c50518969B93d2C6B76bf5309790); // data uint256 public registrationFee_ = 10 finney; // price to register a name uint256 public affiliateFee_ = 500 finney; // price to become an affiliate uint256 public pID_; // total number of players // (addr => pID) returns player id by address mapping (address => uint256) public pIDxAddr_; // (name => pID) returns player id by name mapping (bytes32 => uint256) public pIDxName_; // (pID => data) player data mapping (uint256 => Player) public plyr_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => nameNum => name) list of names a player owns mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // registered games mapping (address => bool) public registeredGames_; struct Player { address addr; bytes32 name; bool hasAff; uint256 aff; uint256 withdrawnAff; uint256 laff; uint256 affT2; uint256 names; } // constructor constructor() public { // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = 0xe0b005384df8f4d80e9a69b6210ec1929a935d97; plyr_[1].name = "sportking"; plyr_[1].hasAff = true; plyr_[1].names = 1; pIDxAddr_[0xe0b005384df8f4d80e9a69b6210ec1929a935d97] = 1; pIDxName_["sportking"] = 1; plyrNames_[1]["sportking"] = true; plyrNameList_[1][1] = "sportking"; pID_ = 1; } // modifiers /// @dev prevents contracts from interacting with fsbook modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin, "Human only"); uint256 _codeLength; assembly { _codeLength := extcodesize(_addr) } require(_codeLength == 0, "Human only"); _; } // TODO: Check address!!! /// @dev Check if caller is one of the owner(s). modifier onlyDevs() { // TODO : CHECK THE ADDRESS!!! require(msg.sender == 0xe0b005384df8f4d80e9a69b6210ec1929a935d97 || msg.sender == 0xe3ff68fb79fee1989fb67eb04e196e361ecaec3e || msg.sender == 0xb914843d2e56722a2c133eff956d1f99b820d468 || msg.sender == 0xc52FA2C9411fCd4f58be2d6725094689C46242f2, "msg sender is not a dev"); _; } /// @dev Check if caller is registered. modifier isRegisteredGame() { require(registeredGames_[msg.sender] == true, "sender is not registered"); _; } // events event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timestamp ); event onNewAffiliate ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 amountPaid, uint256 timestamp ); event onUseOldName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 timestamp ); event onGameRegistered ( address indexed gameAddress, bool enabled, uint256 timestamp ); event onWithdraw ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, uint256 amount, uint256 timestamp ); // getters: function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } // public functions: /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode) external payable isHuman() { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } function registerNameXaddr(string _nameString, address _affCode) external payable isHuman() { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } function registerNameXname(string _nameString, bytes32 _affCode) external payable isHuman() { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer); } function registerAffiliate() external payable isHuman() { // make sure name fees paid require (msg.value >= affiliateFee_, "umm..... you have to pay the name fee"); // set up address address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require (_pID > 0, "you need to be registered"); require (plyr_[_pID].hasAff == false, "already registered as affiliate"); FSKingCorp.deposit.value(msg.value)(); plyr_[_pID].hasAff = true; bytes32 _name = plyr_[_pID].name; // fire event emit onNewAffiliate(_pID, _addr, _name, msg.value, now); } function registerGame(address _contract, bool _enable) external isHuman() onlyDevs() { registeredGames_[_contract] = _enable; emit onGameRegistered(_contract, _enable, now); } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) external isHuman() { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; emit onUseOldName(_pID, _addr, _name, now); } // deposit affiliate to a code function depositAffiliate(uint256 _pID) external payable isRegisteredGame() { require(plyr_[_pID].hasAff == true, "Not registered as affiliate"); uint256 value = msg.value; plyr_[_pID].aff = value.add(plyr_[_pID].aff); } // withdraw money function withdraw() external isHuman() { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; bytes32 _name = plyr_[_pID].name; require(_pID != 0, "need to be registered"); uint256 _remainValue = (plyr_[_pID].aff).sub(plyr_[_pID].withdrawnAff); if (_remainValue > 0) { plyr_[_pID].withdrawnAff = plyr_[_pID].aff; address(msg.sender).transfer(_remainValue); } emit onWithdraw(_pID, _addr, _name, _remainValue, now); } // core logics: function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; plyr_[_pID].affT2 = _affID; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // TODO: MODIFY THIS // registration fee goes directly to community rewards //FSKingCorp.deposit.value(address(this).balance)(); FSKingCorp.deposit.value(msg.value)(); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } // external calls: function getPlayerID(address _addr) external isRegisteredGame() returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function setPlayerLAff(uint256 _pID, uint256 _lAff) external isRegisteredGame() { if (_pID != _lAff && plyr_[_pID].laff != _lAff) { plyr_[_pID].laff = _lAff; } } function getPlayerAffT2(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].affT2); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getPlayerHasAff(uint256 _pID) external view returns (bool) { return (plyr_[_pID].hasAff); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function getAffiliateFee() external view returns (uint256) { return (affiliateFee_); } function setRegistrationFee(uint256 _fee) external onlyDevs() { registrationFee_ = _fee; } function setAffiliateFee(uint256 _fee) external onlyDevs() { affiliateFee_ = _fee; } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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, "SafeMath mul failed"); return c; } /** * @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, "SafeMath sub failed"); 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, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
core logics: if names already has been used, require that current msg sender owns the name add name to player profile, registry, and name book
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; plyr_[_pID].affT2 = _affID; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } }
417,045
pragma solidity ^0.4.18; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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. */ contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ 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(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){ bool match_ = true; for (var i=0; i<prefix.length; i++){ if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <arachnid@notdot.net> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // 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)) } } /* * @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 returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @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 returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint len; uint div = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / div; if (b < 0x80) { ret = b; len = 1; } else if(b < 0xE0) { ret = b & 0x1F; len = 2; } else if(b < 0xF0) { ret = b & 0x0F; len = 3; } else { ret = b & 0x07; len = 4; } // Check for truncated codepoints if (len > self._len) { return 0; } for (uint i = 1; i < len; i++) { div = div / 256; b = (word / div) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := sha3(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let len := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let len := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, len), sha3(needleptr, len)) } } if (equal) { self._len -= needle._len; } return self; } // 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; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 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) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @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 Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after 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 rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after 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` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @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 count) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { count++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ 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 Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint len = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) len += parts[i]._len; var ret = new string(len); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } contract SafeMath { function safeToAdd(uint a, uint b) pure internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) pure internal returns (uint) { require(safeToAdd(a, b)); return (a + b); } function safeToSubtract(uint a, uint b) pure internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) pure internal returns (uint) { require(safeToSubtract(a, b)); return (a - b); } } /** * @title token * @dev token function singnature */ contract token { function transfer(address receiver, uint amount){ receiver; amount; } } /** * @title Etherwow * @dev user choose a num in [2,99] system generate a num in [1,100], if num user choosed > num system generated, user win, otherwise user lose */ contract Etherwow is usingOraclize, SafeMath { using strings for *; /* * checks user profit, bet size and user number is within range */ modifier betIsValid(uint _betSize, uint _userNumber) { require(((((_betSize * (100-(safeSub(_userNumber,1)))) / (safeSub(_userNumber,1))+_betSize))*houseEdge/houseEdgeDivisor)-_betSize <= maxProfit && _betSize >= minBet && _userNumber >= minNumber && _userNumber <= maxNumber); _; } /* * checks game is currently active */ modifier gameIsActive { require(gamePaused == false); _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } /* * checks only owner address is calling */ modifier onlyOwner { require(msg.sender == owner); _; } /* * checks only owner address is calling */ modifier onlyOwnerOrOperator { require((msg.sender == owner || msg.sender == operator.addr) && msg.sender != 0x0); _; } /* * token vars */ token public jackpotToken; uint public jackpotTokenEthRate; uint public jackpotTokenWinRewardRate; uint public jackpotTokenLoseRewardRate; uint constant rewardRateDivisor = 1000; uint jackpotTokenReward; /* * game vars */ uint constant public maxProfitDivisor = 1000000; uint constant public houseEdgeDivisor = 1000; uint constant public maxNumber = 99; uint constant public minNumber = 2; bool public gamePaused; uint32 public gasForOraclize; address public owner; uint public contractBalance; uint public houseEdge; uint public maxProfit; uint public maxProfitAsPercentOfHouse; uint public minBet; uint public maxPendingPayouts; uint public randomQueryID; uint public randomGenerateMethod; string private randomApiKey; /* init discontinued contract data */ uint public totalBets = 0; uint public totalWeiWon = 0; uint public totalWeiWagered = 0; /* access control */ Operator public operator; struct Operator{ address addr; bool refundPermission; /* true - have permission, false - don't have permission */ uint refundAmtApprove; /* when refundAmtApprove not enough, use ownerModOperator() to set again */ } /* * user vars */ mapping (bytes32 => address) public userAddress; mapping (bytes32 => address) public userTempAddress; mapping (bytes32 => bytes32) public userBetId; mapping (bytes32 => uint) public userBetValue; mapping (bytes32 => uint) public userTempBetValue; mapping (bytes32 => uint) public userDieResult; mapping (bytes32 => uint) public userNumber; mapping (address => uint) public userPendingWithdrawals; mapping (bytes32 => uint) public userProfit; mapping (bytes32 => uint) public userTempReward; /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send, 5=pending, 6=manual refund */ mapping (bytes32 => uint8) public betStatus; /* * events */ /* log bets + output to web3 for precise 'payout on win' field in UI */ event LogBet(bytes32 indexed BetID, address indexed UserAddress, uint indexed RewardValue, uint ProfitValue, uint BetValue, uint UserNumber, uint RandomQueryID); /* output to web3 UI on bet result*/ event LogResult(bytes32 indexed BetID, address indexed UserAddress, uint UserNumber, uint DiceResult, uint Value, uint tokenReward, uint8 Status, uint RandomGenerateMethod, bytes Proof, uint indexed SerialNumberOfResult); /* log manual refunds */ event LogRefund(bytes32 indexed BetID, address indexed UserAddress, uint indexed RefundValue); /* log owner transfers */ event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred); /* * init */ function Etherwow() { owner = msg.sender; oraclize_setNetwork(networkID_auto); /* init 990 = 99% (1% houseEdge)*/ ownerSetHouseEdge(990); /* init 10,000 = 1% */ ownerSetMaxProfitAsPercentOfHouse(10000); /* init min bet (0.1 ether) */ ownerSetMinBet(100000000000000000); /* init gas for oraclize */ gasForOraclize = 300000; /* init gas price for callback (default 20 gwei)*/ oraclize_setCustomGasPrice(20000000000 wei); /* defult random num generation method 0-random.org */ randomGenerateMethod = 0; } /* * @dev generate a true random num, two methods are provide, to avoid single point failure * randomGenerateMethod = 0 - random num generate from random.org * randomGenerateMethod = 1 - random num generate from oraclize service * @return oraclize queryId */ function generateRandomNum() internal returns(bytes32){ /* random num solution from random.org */ if (randomGenerateMethod == 0){ randomQueryID += 1; string memory queryString1 = "[URL] ['json(https://api.random.org/json-rpc/1/invoke).result.random[\"serialNumber\",\"data\"]', '\\n{\"jsonrpc\":\"2.0\",\"method\":\"generateSignedIntegers\",\"params\":{\"apiKey\":"; string memory queryString1_1 = ",\"n\":1,\"min\":1,\"max\":100,\"replacement\":true,\"base\":10${[identity] \"}\"},\"id\":"; queryString1 = queryString1.toSlice().concat(randomApiKey.toSlice()); queryString1 = queryString1.toSlice().concat(queryString1_1.toSlice()); string memory queryString2 = uint2str(randomQueryID); string memory queryString3 = "${[identity] \"}\"}']"; string memory queryString1_2 = queryString1.toSlice().concat(queryString2.toSlice()); string memory queryString1_2_3 = queryString1_2.toSlice().concat(queryString3.toSlice()); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); return oraclize_query("nested", queryString1_2_3, gasForOraclize); } // /* random num solution from oraclize(by default), prove fair paper: http://www.oraclize.it/papers/random_datasource-rev1.pdf */ // if (randomGenerateMethod == 1){ // randomQueryID += 1; // uint N = 8; /* number of random bytes we want the datasource to return */ // uint delay = 0; /* number of seconds to wait before the execution takes place */ // oraclize_setProof(proofType_Ledger); // return oraclize_newRandomDSQuery(delay, N, gasForOraclize); /* this function internally generates the correct oraclize_query and returns its queryId */ // } } /* * @dev validate roll dice request, and log the bet info * @param number player choosen, from [2,99] * @param user address */ function userRollDice(uint rollUnder, address userAddr) public payable gameIsActive betIsValid(msg.value, rollUnder) { require((msg.value == 100000000000000000 && rollUnder == 76) || (msg.value == 200000000000000000 && rollUnder == 51) || (msg.value == 1000000000000000000 && rollUnder == 31) || (msg.value == 500000000000000000 && rollUnder == 16)); bytes32 rngId = generateRandomNum(); /* map bet id to this oraclize query */ userBetId[rngId] = rngId; /* map user lucky number to this oraclize query */ userNumber[rngId] = rollUnder; /* map value of wager to this oraclize query */ userBetValue[rngId] = msg.value; /* map user address to this oraclize query */ userAddress[rngId] = userAddr; /* safely map user profit to this oraclize query */ if (msg.value == 100000000000000000 && rollUnder == 76){ userProfit[rngId] = 20000000000000000; } if (msg.value == 200000000000000000 && rollUnder == 51){ userProfit[rngId] = 160000000000000000; } if (msg.value == 1000000000000000000 && rollUnder == 31){ userProfit[rngId] = 2000000000000000000; } if (msg.value == 500000000000000000 && rollUnder == 16){ userProfit[rngId] = 2500000000000000000; } /* safely increase maxPendingPayouts liability - calc all pending payouts under assumption they win */ maxPendingPayouts = safeAdd(maxPendingPayouts, userProfit[rngId]); /* check contract can payout on win */ require(maxPendingPayouts < contractBalance); /* bet status = 5-pending */ betStatus[rngId] = 5; /* provides accurate numbers for web3 and allows for manual refunds in case of no oraclize __callback */ emit LogBet(userBetId[rngId], userAddress[rngId], safeAdd(userBetValue[rngId], userProfit[rngId]), userProfit[rngId], userBetValue[rngId], userNumber[rngId], randomQueryID); } /* * @dev oraclize callback, only oraclize can call, payout should in active status * @param queryId * @param query result * @param query proof */ function __callback(bytes32 myid, string result, bytes proof) public onlyOraclize { /* user address mapped to query id does not exist */ require(userAddress[myid]!=0x0); /* random num solution from random.org(by default) */ if (randomGenerateMethod == 0){ /* keep oraclize honest by retrieving the serialNumber from random.org result */ var sl_result = result.toSlice(); sl_result.beyond("[".toSlice()).until("]".toSlice()); uint serialNumberOfResult = parseInt(sl_result.split(', '.toSlice()).toString()); /* map random result to user */ userDieResult[myid] = parseInt(sl_result.beyond("[".toSlice()).until("]".toSlice()).toString()); } // /* random num solution from oraclize */ // if (randomGenerateMethod == 1){ // uint maxRange = 100; this is the highest uint we want to get. It should never be greater than 2^(8*N), where N is the number of random bytes we had asked the datasource to return // userDieResult[myid] = uint(sha3(result)) % maxRange + 1; /* this is an efficient way to get the uint out in the [0, maxRange] range */ // } /* get the userAddress for this query id */ userTempAddress[myid] = userAddress[myid]; /* delete userAddress for this query id */ delete userAddress[myid]; /* map the userProfit for this query id */ userTempReward[myid] = userProfit[myid]; /* set userProfit for this query id to 0 */ userProfit[myid] = 0; /* safely reduce maxPendingPayouts liability */ maxPendingPayouts = safeSub(maxPendingPayouts, userTempReward[myid]); /* map the userBetValue for this query id */ userTempBetValue[myid] = userBetValue[myid]; /* set userBetValue for this query id to 0 */ userBetValue[myid] = 0; /* total number of bets */ totalBets += 1; /* total wagered */ totalWeiWagered += userTempBetValue[myid]; /* * refund * if result is 0 result is empty or no proof refund original bet value * if refund fails save refund value to userPendingWithdrawals */ if(userDieResult[myid] == 0 || bytes(result).length == 0 || bytes(proof).length == 0){ /* Status: 0=lose, 1=win, 2=win + failed send, 3=refund, 4=refund + failed send*/ /* 3 = refund */ betStatus[myid] = 3; /* * send refund - external call to an untrusted contract * if send fails map refund value to userPendingWithdrawals[address] * for withdrawal later via userWithdrawPendingTransactions */ if(!userTempAddress[myid].send(userTempBetValue[myid])){ /* 4 = refund + failed send */ betStatus[myid] = 4; /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], userTempBetValue[myid]); } jackpotTokenReward = 0; emit LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], jackpotTokenReward, betStatus[myid], randomGenerateMethod, proof, serialNumberOfResult); return; } /* * pay winner * update contract balance to calculate new max bet * send reward * if send of reward fails save value to userPendingWithdrawals */ if(userDieResult[myid] < userNumber[myid]){ /* safely reduce contract balance by user profit */ contractBalance = safeSub(contractBalance, userTempReward[myid]); /* update total wei won */ totalWeiWon = safeAdd(totalWeiWon, userTempReward[myid]); /* safely calculate payout via profit plus original wager */ userTempReward[myid] = safeAdd(userTempReward[myid], userTempBetValue[myid]); /* 1 = win */ betStatus[myid] = 1; /* update maximum profit */ setMaxProfit(); if (jackpotTokenWinRewardRate > 0) { /* calculate win token return */ jackpotTokenReward = userTempBetValue[myid]*jackpotTokenEthRate*jackpotTokenWinRewardRate/rewardRateDivisor; /* transfer token to user */ jackpotToken.transfer(userTempAddress[myid], jackpotTokenReward); } /* * send win - external call to an untrusted contract * if send fails map reward value to userPendingWithdrawals[address] * for withdrawal later via userWithdrawPendingTransactions */ if(!userTempAddress[myid].send(userTempReward[myid])){ /* 2 = win + failed send */ betStatus[myid] = 2; /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], userTempReward[myid]); } emit LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], jackpotTokenReward, betStatus[myid], randomGenerateMethod, proof, serialNumberOfResult); return; } /* * no win * send 1 wei to a losing bet * update contract balance to calculate new max bet */ if(userDieResult[myid] >= userNumber[myid]){ /* 0 = lose */ betStatus[myid] = 0; /* * safe adjust contractBalance * setMaxProfit * send 1 wei to losing bet */ contractBalance = safeAdd(contractBalance, (userTempBetValue[myid]-1)); /* update maximum profit */ setMaxProfit(); if (jackpotTokenLoseRewardRate > 0){ /* calculate token reward */ jackpotTokenReward = userTempBetValue[myid]*jackpotTokenEthRate*safeSub(100,userNumber[myid])*jackpotTokenLoseRewardRate/(rewardRateDivisor*100); /* transfer token to user */ jackpotToken.transfer(userTempAddress[myid], jackpotTokenReward); } /* * send 1 wei - external call to an untrusted contract */ if(!userTempAddress[myid].send(1)){ /* if send failed let user withdraw via userWithdrawPendingTransactions */ userPendingWithdrawals[userTempAddress[myid]] = safeAdd(userPendingWithdrawals[userTempAddress[myid]], 1); } emit LogResult(userBetId[myid], userTempAddress[myid], userNumber[myid], userDieResult[myid], userTempBetValue[myid], jackpotTokenReward, betStatus[myid], randomGenerateMethod, proof, serialNumberOfResult); return; } } /* * @dev in case of a failed refund or win send, user can withdraw later * @return true - withdraw success, false - withdraw failed */ function userWithdrawPendingTransactions() public gameIsActive returns (bool) { uint withdrawAmount = userPendingWithdrawals[msg.sender]; userPendingWithdrawals[msg.sender] = 0; /* external call to untrusted contract */ if (msg.sender.call.value(withdrawAmount)()) { return true; } else { /* if send failed revert userPendingWithdrawals[msg.sender] = 0; */ /* user can try to withdraw again later */ userPendingWithdrawals[msg.sender] = withdrawAmount; return false; } } /* * @dev in case of a failed refund or win send, user can check pending withdraw * @param address to check * @return pending withdraw amount */ function userGetPendingTxByAddress(address addressToCheck) public constant returns (uint) { return userPendingWithdrawals[addressToCheck]; } /* * @dev sets max profit */ function setMaxProfit() internal { maxProfit = (contractBalance*maxProfitAsPercentOfHouse)/maxProfitDivisor; } /* * @dev fallback method */ function () payable onlyOwnerOrOperator { /* safely update contract balance */ contractBalance = safeAdd(contractBalance, msg.value); /* update the maximum profit */ setMaxProfit(); } /* * @dev owner can set operator & permission * if want to revoke a permission, just set address to "0x0" * @param operator address * @param operator transfer permission * @param operator transfer approve amt * @param operator refund permission * @param operator refund approve amt */ function ownerModOperator(address newAddress, bool newRefundPermission, uint newRefundAmtApprove) public onlyOwner { operator.addr = newAddress; operator.refundPermission = newRefundPermission; operator.refundAmtApprove = newRefundAmtApprove; } /* * @dev onlyOwnerOrOperator set gas price for oraclize callback */ function ownerSetCallbackGasPrice(uint newCallbackGasPrice) public onlyOwnerOrOperator { oraclize_setCustomGasPrice(newCallbackGasPrice); } /* * @dev onlyOwnerOrOperator set gas limit for oraclize query */ function ownerSetOraclizeSafeGas(uint32 newSafeGasToOraclize) public onlyOwnerOrOperator { gasForOraclize = newSafeGasToOraclize; } /* * @dev onlyOwnerOrOperator adjust contract balance variable (only used for max profit calc) */ function ownerUpdateContractBalance(uint newContractBalanceInWei) public onlyOwnerOrOperator { contractBalance = newContractBalanceInWei; } /* * @dev owner set houseEdge */ function ownerSetHouseEdge(uint newHouseEdge) public onlyOwnerOrOperator { if(msg.sender == operator.addr && newHouseEdge > 990) throw; houseEdge = newHouseEdge; } /* * @dev onlyOwnerOrOperator set maxProfitAsPercentOfHouse */ function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public onlyOwnerOrOperator { /* restrict each bet to a maximum profit of 5% contractBalance */ require(newMaxProfitAsPercent <= 50000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } /* * @dev onlyOwnerOrOperator set minBet */ function ownerSetMinBet(uint newMinimumBet) public onlyOwnerOrOperator { minBet = newMinimumBet; } /* * @dev owner transfer ether */ function ownerTransferEther(address sendTo, uint amount) public onlyOwner { /* safely update contract balance when sending out funds*/ contractBalance = safeSub(contractBalance, amount); /* update max profit */ setMaxProfit(); sendTo.transfer(amount); emit LogOwnerTransfer(sendTo, amount); } /* * @dev manual refund * only onlyOwnerOrOperator address can do manual refund * used only if bet placed but not execute payout method after stock market close * filter LogBet by address and/or userBetId, do manual refund only when meet below conditions: * 1. bet status should be 5-pending; * 2. record should in logBet; * 3. record should not in logResult; * 4. record should not in logRefund; * if LogResult exists user should use the withdraw pattern userWithdrawPendingTransactions * if LogRefund exists means manual refund has been done before * @param betId * @param address sendTo * @param original user profit * @param original bet value */ function ownerRefundUser(bytes32 originalUserBetId, address sendTo, uint originalUserProfit, uint originalUserBetValue) public onlyOwnerOrOperator { /* check operator permission */ require(msg.sender == owner || (msg.sender == operator.addr && operator.refundPermission == true && safeToSubtract(operator.refundAmtApprove, originalUserBetValue))); /* status should be 5-pending */ require(betStatus[originalUserBetId] == 5); /* safely reduce pendingPayouts by userProfit[rngId] */ maxPendingPayouts = safeSub(maxPendingPayouts, originalUserProfit); /* send refund */ sendTo.transfer(originalUserBetValue); /* decrease approve amt if it's triggered by operator(no need to use safesub here, since passed above require() statement) */ if(msg.sender == operator.addr){ operator.refundAmtApprove = operator.refundAmtApprove - originalUserBetValue; } /* update betStatus = 6-manual refund */ betStatus[originalUserBetId] = 6; /* log refunds */ emit LogRefund(originalUserBetId, sendTo, originalUserBetValue); } /* * @dev onlyOwnerOrOperator set system emergency pause * @param true: pause, false: not pause */ function ownerPauseGame(bool newStatus) public onlyOwnerOrOperator { gamePaused = newStatus; } /* * @dev owner set new owner * @param new owner address */ function ownerChangeOwner(address newOwner) public onlyOwner { owner = newOwner; } /* * @dev onlyOwnerOrOperator set random.org api key * @param new api key */ function ownerSetRandomApiKey(string newApiKey) public onlyOwnerOrOperator { randomApiKey = newApiKey; } /* * @dev onlyOwnerOrOperator can set randomGenerateMethod * @param 0-random num solution from random.org, 1-random num solution from oraclize */ function ownerSetRandomGenerateMethod(uint newRandomGenerateMethod) public onlyOwnerOrOperator { randomGenerateMethod = newRandomGenerateMethod; } /* * @dev onlyOwnerOrOperator can set jackpotToken * @param jackpotToken address * @param ether to token rate * @param win reward rate, defult 10(divisor 1000) * @param lose reward rate, defult 1000(divisor 1000) */ function ownerSetJackpotToken(address newTokenAddr, uint newTokenEthRate, uint newWinRewardRate, uint newLoseRewardRate) public onlyOwnerOrOperator{ jackpotToken = token(newTokenAddr); jackpotTokenEthRate = newTokenEthRate; jackpotTokenWinRewardRate = newWinRewardRate; jackpotTokenLoseRewardRate = newLoseRewardRate; } /* * @dev transfer token * @param to address * @param token amount */ function ownerTransferJackpotToken(address toAddress, uint amount ) public onlyOwner{ jackpotToken.transfer(toAddress, amount); } /* * @dev owner selfdestruct contract ***BE CAREFUL! EMERGENCY ONLY / CONTRACT UPGRADE*** */ function ownerkill() public onlyOwner { selfdestruct(owner); } }
owner can set operator & permission if want to revoke a permission, just set address to "0x0" operator address operator transfer permission operator transfer approve amt operator refund permission operator refund approve amt/
function ownerModOperator(address newAddress, bool newRefundPermission, uint newRefundAmtApprove) public onlyOwner { operator.addr = newAddress; operator.refundPermission = newRefundPermission; operator.refundAmtApprove = newRefundAmtApprove; }
12,184,520
./partial_match/42/0x614eEE0cB8D63a505ED41581bAB52841bd5ef820/sources/Tokenize.sol
Remove an address from the blacklist _address The address to be removed from the blacklist/
function removeBlackList(address[] memory _address) public onlyOwner { for (uint256 i = 0; i < _address.length; i++) { if (isBlackListed[_address[i]]) { isBlackListed[_address[i]] = false; blackListCount--; emit RemovedBlackList(_address[i]); } } }
3,342,452
./full_match/4/0x5e30D983392358DB09f02Cd10d13984dD97DCe2a/sources/project_/contracts/RouterV2.sol
SWAP requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = MainLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? MainLibrary.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(MainLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } }
817,021
// File: @uniswap\lib\contracts\libraries\TransferHelper.sol pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } pragma solidity >=0.6.4; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\interfaces\IPancakeRouter01.sol pragma solidity >=0.6.2; interface IPancakeRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: contracts\interfaces\IPancakeRouter02.sol pragma solidity >=0.6.2; interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: contracts\interfaces\IPancakeFactory.sol pragma solidity >=0.5.0; interface IPancakeFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function INIT_CODE_PAIR_HASH() external view returns (bytes32); } // File: contracts\libraries\SafeMath.sol pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } // File: contracts\interfaces\IPancakePair.sol pragma solidity >=0.5.0; interface IPancakePair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts\libraries\PancakeLibrary.sol pragma solidity >=0.5.0; library PancakeLibrary { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); pairFor(factory, tokenA, tokenB); (uint reserve0, uint reserve1,) = IPancakePair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts\interfaces\IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // File: contracts\interfaces\IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts\PancakeRouter.sol pragma solidity =0.6.6; contract UniswapV2Router is IPancakeRouter02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; address public feeReceiver; uint256 public theFee; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'PancakeRouter: EXPIRED'); _; } constructor(address _factory, address _WETH, address _feeReceiver, uint256 _theFee) public { factory = _factory; WETH = _WETH; feeReceiver = _feeReceiver; theFee = _theFee; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // change fee beneficiary function changeReceiver(address _feeReceiver) public { require(msg.sender == feeReceiver, "not owner?"); feeReceiver = _feeReceiver; } // change fee function changeFee(uint256 _theFee) public { require(msg.sender == feeReceiver, "not owner?"); require(_theFee < 500, "fee to high"); theFee = _theFee; } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IPancakeFactory(factory).getPair(tokenA, tokenB) == address(0)) { IPancakeFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = PancakeLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = PancakeLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'PancakeRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = PancakeLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'PancakeRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } // function addLiquidity( // address tokenA, // address tokenB, // uint amountADesired, // uint amountBDesired, // uint amountAMin, // uint amountBMin, // address to, // uint deadline // ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { // (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); // address pair = PancakeLibrary.pairFor(factory, tokenA, tokenB); // TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); // TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); // liquidity = IPancakePair(pair).mint(to); // } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = PancakeLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IPancakePair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = PancakeLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IPancakePair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = PancakeLibrary.pairFor(factory, tokenA, tokenB); IPancakePair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IPancakePair(pair).burn(to); (address token0,) = PancakeLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'PancakeRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'PancakeRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = PancakeLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IPancakePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = PancakeLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IPancakePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = PancakeLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IPancakePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = PancakeLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? PancakeLibrary.pairFor(factory, output, path[i + 2]) : _to; IPancakePair(PancakeLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); if(theFee > 0 && input != 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2){ uint amountIn_fee = amounts[i]; theAmountis = amountIn_fee; // 10000000000000000* uint256 theRam1 = amountIn_fee.mul(theFee).div(10000); IBEP20(input).transferFrom(msg.sender, feeReceiver, theRam1); } } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = PancakeLibrary.getAmountsOut(factory, amountIn, path); uint256 newAmountOut = amountOutMin.mul(theFee).div(10000); require(amounts[amounts.length - 1] >= amountOutMin.sub(newAmountOut), 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = PancakeLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'PancakeRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'PancakeRouter: INVALID_PATH'); uint256 theRam1 = msg.value.mul(theFee).div(10000); payable(feeReceiver).transfer(theRam1); amounts = PancakeLibrary.getAmountsOut(factory, msg.value.sub(theRam1), path); uint256 newAmountOut = amountOutMin.mul(theFee).div(10000); require(amounts[amounts.length - 1] >= amountOutMin.sub(newAmountOut), 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH'); amounts = PancakeLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'PancakeRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH'); amounts = PancakeLibrary.getAmountsOut(factory, amountIn, path); uint256 newAmountOut = amountOutMin.mul(theFee).div(10000); require(amounts[amounts.length - 1] >= amountOutMin.sub(newAmountOut), 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'PancakeRouter: INVALID_PATH'); amounts = PancakeLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'PancakeRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } uint public theAmountis; // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = PancakeLibrary.sortTokens(input, output); IPancakePair pair = IPancakePair(PancakeLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = PancakeLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? PancakeLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); if(theFee > 0 && input != 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2){ uint amountIn_fee = amountInput; theAmountis = amountIn_fee; // 10000000000000000* uint256 theRam1 = amountInput.mul(theFee).div(10000); IBEP20(input).transferFrom(msg.sender, feeReceiver, theRam1); } } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'PancakeRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(PancakeLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'PancakeRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, PancakeLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); uint256 newAmountOut = amountOutMin.mul(theFee).div(10000); require(amountOut >= amountOutMin.sub(newAmountOut), 'PancakeRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return PancakeLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return PancakeLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return PancakeLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return PancakeLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return PancakeLibrary.getAmountsIn(factory, amountOut, path); } }
SWAP (supporting fee-on-transfer tokens) requires the initial amount to have already been sent to the first pair 10000000000000000
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = PancakeLibrary.sortTokens(input, output); IPancakePair pair = IPancakePair(PancakeLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = PancakeLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? PancakeLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); if(theFee > 0 && input != 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2){ uint amountIn_fee = amountInput; theAmountis = amountIn_fee; uint256 theRam1 = amountInput.mul(theFee).div(10000); IBEP20(input).transferFrom(msg.sender, feeReceiver, theRam1); } }
1,720,521
// SPDX-License-Identifier: --GRISE-- pragma solidity =0.7.6; import './Interfaces.sol'; import './Randomness.sol'; contract LiquidityTransformer { using SafeMathLT for uint256; using SafeMathLT for uint128; Randomness public randomness; IGriseToken public GRISE_CONTRACT; RefundSponsorI public REFUND_SPONSOR; UniswapRouterV2 public constant UNISWAP_ROUTER = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // mainnet ); address payable constant TEAM_ADDRESS = 0xa377433831E83C7a4Fa10fB75C33217cD7CABec2; address payable constant DEV_ADDRESS = 0xcD8DcbA8e4791B19719934886A8bA77EA3fad447; address public TOKEN_DEFINER; address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint8 constant INVESTMENT_DAYS = 50; uint8 constant MAX_DAY_SLOT = 147; uint128 constant THRESHOLD_LIMIT_MIN = 100000000000000000 wei; uint128 constant THRESHOLD_LIMIT_MAX = 20 ether; uint256 public TEAM_ETHER; uint128 constant MIN_INVEST = 100000000000000000 wei; uint128 constant DAILY_MAX_SUPPLY = 12000; uint256 constant REI_PER_GRISE = 10 ** uint256(18); struct Globals { uint64 generatedDays; uint64 preparedReferrals; uint256 totalTransferTokens; uint256 totalWeiContributed; uint256 totalReferralTokens; } Globals public g; mapping(uint256 => uint256) dailyMinSupply; mapping(uint256 => uint256) dailyMaxSupply; mapping(uint256 => uint256) public dailyTotalSupply; mapping(uint256 => uint256) public dailyTotalInvestment; mapping(uint256 => uint256) public dailySlots; uint256 public totalInvestment; uint8 public totalTransactions; uint8 constant GAS_REFUND_THRESHOLD = 200; mapping(uint256 => uint256) public investorAccountCount; mapping(uint256 => mapping(uint256 => address)) public investorAccounts; mapping(address => mapping(uint256 => uint256)) public investorBalances; mapping(address => mapping(uint256 => uint256)) public investorBalancesRecord; mapping(address => uint256) public referralAmount; mapping(address => uint256) public referralTokens; mapping(address => uint256) public investorTotalBalance; mapping(address => uint256) originalInvestment; uint256 public referralAccountCount; uint256 public uniqueInvestorCount; mapping (uint256 => address) public uniqueInvestors; mapping (uint256 => address) public referralAccounts; event GeneratedRandomSupply( uint256 indexed investmentDay, uint256 randomSupply ); event GeneratedStaticSupply( uint256 indexed investmentDay, uint256 staticSupply ); event ReferralAdded( address indexed referral, address indexed referee, uint256 amount ); event UniSwapResult( uint256 amountToken, uint256 amountETH, uint256 liquidity ); event GriseReservation( address indexed sender, uint256 indexed investmentDay, uint256 amount ); modifier afterInvestmentPhase() { require( _currentLPDay() > INVESTMENT_DAYS, 'GRISE: ongoing investment phase' ); _; } modifier afterUniswapTransfer() { require ( g.generatedDays > 0 && g.totalWeiContributed == 0, 'GRISE: forward liquidity first' ); _; } modifier investmentDaysRange(uint256 _investmentDay) { require( _investmentDay > 0 && _investmentDay <= INVESTMENT_DAYS, 'GRISE: not in initial investment days range' ); _; } modifier onlyFundedDays(uint256 _investmentDay) { require( dailyTotalInvestment[_investmentDay] > 0, 'GRISE: no investments on that day' ); _; } modifier refundSponsorDynamic() { uint256 gasStart = gasleft(); _; uint256 gasSpent = (21000 + gasStart - gasleft()).mul(tx.gasprice); gasSpent = msg.value.div(10) > gasSpent ? gasSpent : msg.value.div(10); if(totalTransactions <= GAS_REFUND_THRESHOLD){ REFUND_SPONSOR.addGasRefund(msg.sender, gasSpent); } } modifier refundSponsorFixed() { uint256 gasStart = gasleft(); _; uint256 gasSpent = (21000 + gasStart - gasleft()).mul(tx.gasprice); gasSpent = gasSpent > 5000000000000000 ? 5000000000000000 : gasSpent; if(totalTransactions <= GAS_REFUND_THRESHOLD){ REFUND_SPONSOR.addGasRefund(msg.sender, gasSpent); } } modifier onlyTokenDefiner() { require( msg.sender == TOKEN_DEFINER, 'GRISE: wrong sender' ); _; } receive() external payable { require ( msg.sender == address(UNISWAP_ROUTER) || msg.sender == TEAM_ADDRESS || msg.sender == DEV_ADDRESS || msg.sender == TOKEN_DEFINER, 'GRISE: direct deposits disabled' ); } function defineToken( address _griseToken ) external onlyTokenDefiner { GRISE_CONTRACT = IGriseToken(_griseToken); } function revokeAccess() external onlyTokenDefiner { TOKEN_DEFINER = address(0x0); } constructor(address _griseToken, Randomness _randomness, address _refundSponsor) { randomness=_randomness; GRISE_CONTRACT = IGriseToken(_griseToken); REFUND_SPONSOR = RefundSponsorI(_refundSponsor); TOKEN_DEFINER = msg.sender; dailyMinSupply[1] = 6000; dailyMinSupply[2] = 6000; dailyMinSupply[3] = 6000; dailyMinSupply[4] = 6000; dailyMinSupply[5] = 2150; dailyMinSupply[6] = 6000; dailyMinSupply[7] = 3650; dailyMinSupply[8] = 6000; dailyMinSupply[9] = 3650; dailyMinSupply[10] = 6000; dailyMinSupply[11] = 3650; dailyMinSupply[12] = 6000; dailyMinSupply[13] = 6000; dailyMinSupply[14] = 2150; dailyMinSupply[15] = 6000; dailyMinSupply[16] = 3650; dailyMinSupply[17] = 6000; dailyMinSupply[18] = 3650; dailyMinSupply[19] = 6000; dailyMinSupply[20] = 2150; dailyMinSupply[21] = 6000; dailyMinSupply[22] = 2150; dailyMinSupply[23] = 6000; dailyMinSupply[24] = 2150; dailyMinSupply[25] = 6000; dailyMinSupply[26] = 2150; dailyMinSupply[27] = 6000; dailyMinSupply[28] = 6000; dailyMinSupply[29] = 3650; dailyMinSupply[30] = 6000; dailyMinSupply[31] = 6000; dailyMinSupply[32] = 2150; dailyMinSupply[33] = 6000; dailyMinSupply[34] = 3650; dailyMinSupply[35] = 6000; dailyMinSupply[36] = 3650; dailyMinSupply[37] = 6000; dailyMinSupply[38] = 2150; dailyMinSupply[39] = 2150; dailyMinSupply[40] = 6000; dailyMinSupply[41] = 3650; dailyMinSupply[42] = 6000; dailyMinSupply[43] = 6000; dailyMinSupply[44] = 2150; dailyMinSupply[45] = 6000; dailyMinSupply[46] = 3650; dailyMinSupply[47] = 2150; dailyMinSupply[48] = 3650; dailyMinSupply[49] = 6000; dailyMinSupply[50] = 6000; dailyMaxSupply[5] = 16850; dailyMaxSupply[14] = 16850; dailyMaxSupply[20] = 16850; dailyMaxSupply[22] = 16850; dailyMaxSupply[24] = 16850; dailyMaxSupply[26] = 16850; dailyMaxSupply[32] = 16850; dailyMaxSupply[38] = 16850; dailyMaxSupply[39] = 16850; dailyMaxSupply[44] = 16850; dailyMaxSupply[47] = 16850; dailyMaxSupply[7] = 11850; dailyMaxSupply[9] = 11850; dailyMaxSupply[11] = 11850; dailyMaxSupply[16] = 11850; dailyMaxSupply[18] = 11850; dailyMaxSupply[29] = 11850; dailyMaxSupply[34] = 11850; dailyMaxSupply[36] = 11850; dailyMaxSupply[41] = 11850; dailyMaxSupply[46] = 11850; dailyMaxSupply[48] = 11850; } // GRISE RESERVATION (EXTERNAL FUNCTIONS) // // ------------------------------------- // /** @dev Performs reservation of GRISE tokens with ETH * @param _investmentDays array of reservation days. * @param _referralAddress referral address for bonus. */ function reserveGrise( uint8[] calldata _investmentDays, address _referralAddress ) external payable refundSponsorDynamic { checkInvestmentDays( _investmentDays, _currentLPDay(), msg.sender, msg.value ); _reserveGrise( _investmentDays, _referralAddress, msg.sender, msg.value ); } /** @notice Allows reservation of GRISE tokens with other ERC20 tokens * @dev this will require LT contract to be approved as spender * @param _tokenAddress address of an ERC20 token to use * @param _tokenAmount amount of tokens to use for reservation * @param _investmentDays array of reservation days * @param _referralAddress referral address for bonus */ function reserveGriseWithToken( address _tokenAddress, uint256 _tokenAmount, uint8[] calldata _investmentDays, address _referralAddress ) external refundSponsorFixed { IERC20Token _token = IERC20Token( _tokenAddress ); _token.transferFrom( msg.sender, address(this), _tokenAmount ); _token.approve( address(UNISWAP_ROUTER), _tokenAmount ); address[] memory _path = preparePath( _tokenAddress ); uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForETH( _tokenAmount, 0, _path, address(this), block.timestamp.add(2 hours) ); checkInvestmentDays( _investmentDays, _currentLPDay(), msg.sender, amounts[1] ); _reserveGrise( _investmentDays, _referralAddress, msg.sender, amounts[1] ); } // GRISE RESERVATION (INTERNAL FUNCTIONS) // // ------------------------------------- // /** @notice Distributes ETH equaly between selected reservation days * @dev this will require LT contract to be approved as a spender * @param _investmentDays array of selected reservation days * @param _referralAddress referral address for bonus * @param _senderAddress address of the investor * @param _senderValue amount of ETH contributed */ function _reserveGrise( uint8[] memory _investmentDays, address _referralAddress, address _senderAddress, uint256 _senderValue ) internal { require( _senderAddress != _referralAddress, 'GRISE: must be a different address' ); require( notContract(_referralAddress), 'GRISE: invalid referral address' ); uint256 _investmentBalance = _referralAddress == address(0x0) ? _senderValue : referralAmount[_referralAddress].add(_senderValue) > THRESHOLD_LIMIT_MAX ?_senderValue.mul(1100).div(1000) :_senderValue.mul(10500).div(10000); uint256 _totalDays = _investmentDays.length; uint256 _dailyAmount = _investmentBalance.div(_totalDays); uint256 _leftOver = _investmentBalance.mod(_totalDays); _addBalance( _senderAddress, _investmentDays[0], _dailyAmount.add(_leftOver) ); for (uint8 _i = 1; _i < _totalDays; _i++) { _addBalance( _senderAddress, _investmentDays[_i], _dailyAmount ); } _trackInvestors( _senderAddress, _investmentBalance ); if (_referralAddress != address(0x0)) { _trackReferrals(_referralAddress, _senderValue); emit ReferralAdded( _referralAddress, _senderAddress, _senderValue ); } originalInvestment[_senderAddress] += _senderValue; g.totalWeiContributed += _senderValue; } /** @notice Allocates investors balance to specific day * @param _senderAddress investors wallet address * @param _investmentDay selected investment day * @param _investmentBalance amount invested (with bonus) */ function _addBalance( address _senderAddress, uint256 _investmentDay, uint256 _investmentBalance ) internal { if (investorBalances[_senderAddress][_investmentDay] == 0) { investorAccounts[_investmentDay][investorAccountCount[_investmentDay]] = _senderAddress; investorAccountCount[_investmentDay]++; } investorBalances[_senderAddress][_investmentDay] += _investmentBalance; investorBalancesRecord[_senderAddress][_investmentDay] += _investmentBalance; dailyTotalInvestment[_investmentDay] += _investmentBalance; totalInvestment += _investmentBalance; totalTransactions++; emit GriseReservation( _senderAddress, _investmentDay, _investmentBalance ); } // GRISE RESERVATION (PRIVATE FUNCTIONS) // // ------------------------------------ // /** @notice Tracks investorTotalBalance and uniqueInvestors * @dev used in _reserveGrise() internal function * @param _investorAddress address of the investor * @param _value ETH amount invested (with bonus) */ function _trackInvestors(address _investorAddress, uint256 _value) private { if (investorTotalBalance[_investorAddress] == 0) { uniqueInvestors[uniqueInvestorCount] = _investorAddress; uniqueInvestorCount++; } investorTotalBalance[_investorAddress] += _value; } /** @notice Tracks referralAmount and referralAccounts * @dev used in _reserveGrise() internal function * @param _referralAddress address of the referrer * @param _value ETH amount referred during reservation */ function _trackReferrals(address _referralAddress, uint256 _value) private { if (referralAmount[_referralAddress] == 0) { referralAccounts[ referralAccountCount] = _referralAddress; referralAccountCount++; } referralAmount[_referralAddress] += _value; } // SUPPLY GENERATION (EXTERNAL FUNCTION) // // ------------------------------------- // /** @notice Allows to generate supply for past funded days * @param _investmentDay investemnt day index (1-50) */ function generateSupply( uint64 _investmentDay ) external investmentDaysRange(_investmentDay) onlyFundedDays(_investmentDay) { require( _investmentDay < _currentLPDay(), 'GRISE: investment day must be in past' ); require( dailyTotalSupply[_investmentDay] == 0, 'GRISE: supply already generated' ); DAILY_MAX_SUPPLY - dailyMinSupply[_investmentDay] == dailyMinSupply[_investmentDay] ? _generateStaticSupply(_investmentDay) : _generateRandomSupply(_investmentDay); } // SUPPLY GENERATION (INTERNAL FUNCTIONS) // // -------------------------------------- // /** @notice Generates supply for days with static supply * @param _investmentDay investemnt day index (1-50) */ function _generateStaticSupply( uint256 _investmentDay ) internal { dailyTotalSupply[_investmentDay] = dailyMinSupply[_investmentDay] * REI_PER_GRISE; g.totalTransferTokens += dailyTotalSupply[_investmentDay]; g.generatedDays++; emit GeneratedStaticSupply( _investmentDay, dailyTotalSupply[_investmentDay] ); } /** @notice Generates supply for days with random supply * @dev uses nreAPI to request random number * @param _investmentDay investemnt day index (1-50) */ function _generateRandomSupply( uint256 _investmentDay ) internal { uint256 ceilingDayMaxSupply = dailyMaxSupply[_investmentDay].sub(dailyMinSupply[_investmentDay]); uint256 randomSupply = randomness.stateRandomNumber() % ceilingDayMaxSupply; g.generatedDays = g.generatedDays + 1; dailyTotalSupply[_investmentDay] = dailyMinSupply[_investmentDay] .add(randomSupply) .mul(REI_PER_GRISE); g.totalTransferTokens = g.totalTransferTokens .add(dailyTotalSupply[_investmentDay]); emit GeneratedRandomSupply( _investmentDay, dailyTotalSupply[_investmentDay] ); } // PRE-LIQUIDITY GENERATION FUNCTION // // --------------------------------- // /** @notice Pre-calculates amount of tokens each referrer will get * @dev must run this for all referrer addresses in batches * converts _referralAmount to _referralTokens based on dailyRatio */ function prepareReferralBonuses( uint256 _referralBatchFrom, uint256 _referralBatchTo ) external afterInvestmentPhase { require( _referralBatchFrom < _referralBatchTo, 'GRISE: incorrect referral batch' ); require ( g.preparedReferrals < referralAccountCount, 'GRISE: all referrals already prepared' ); uint256 _totalRatio = g.totalTransferTokens.div(g.totalWeiContributed); for (uint256 i = _referralBatchFrom; i < _referralBatchTo; i++) { address _referralAddress = referralAccounts[i]; uint256 _referralAmount = referralAmount[_referralAddress]; if (referralAmount[_referralAddress] > 0) { referralAmount[_referralAddress] = 0; if (_referralAmount >= THRESHOLD_LIMIT_MIN) { _referralAmount >= THRESHOLD_LIMIT_MAX ? _fullReferralBonus(_referralAddress, _referralAmount, _totalRatio) : _familyReferralBonus(_referralAddress, _referralAmount, _totalRatio); g.totalReferralTokens = g.totalReferralTokens.add( referralTokens[_referralAddress] ); } g.preparedReferrals++; } } } /** @notice performs token allocation for 10% of referral amount * @dev after liquidity is formed referrer can withdraw this amount */ function _fullReferralBonus(address _referralAddress, uint256 _referralAmount, uint256 _ratio) internal { referralTokens[_referralAddress] = _referralAmount.div(10).mul(_ratio); } /** @notice performs token allocation for 5% of referral amount * @dev after liquidity is formed referrer can withdraw this amount */ function _familyReferralBonus(address _referralAddress, uint256 _referralAmount, uint256 _ratio) internal { referralTokens[_referralAddress] = _referralAmount.div(20).mul(_ratio); } // LIQUIDITY GENERATION FUNCTION // // ----------------------------- // /** @notice Creates initial liquidity on Uniswap by forwarding * reserved tokens equivalent to ETH contributed to the contract * @dev check addLiquidityETH documentation */ function forwardLiquidity(/*🦄*/) external afterInvestmentPhase { require( g.generatedDays == fundedDays(), 'GRISE: must generate supply for all days' ); require ( g.preparedReferrals == referralAccountCount, 'GRISE: must prepare all referrals' ); require ( g.totalTransferTokens > 0, 'GRISE: must have tokens to transfer' ); uint256 _balance = g.totalWeiContributed; uint256 _buffer = g.totalTransferTokens + g.totalReferralTokens; uint256 _bounty = _buffer.mul(8).div(100); _balance = _balance.sub( _teamContribution( _balance.mul(15).div(100) ) ); _buffer = _buffer.mul(_balance).div( g.totalWeiContributed ); _bounty = _bounty.add(_buffer.mul(8).div(100)); GRISE_CONTRACT.mintSupply( address(this), _buffer ); GRISE_CONTRACT.mintSupply( TEAM_ADDRESS, _bounty ); GRISE_CONTRACT.approve( address(UNISWAP_ROUTER), _buffer ); ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) = UNISWAP_ROUTER.addLiquidityETH{value: _balance}( address(GRISE_CONTRACT), _buffer, 0, 0, address(0x0), block.timestamp.add(2 hours) ); g.totalTransferTokens = 0; g.totalReferralTokens = 0; g.totalWeiContributed = 0; emit UniSwapResult( amountToken, amountETH, liquidity ); } // GRISE TOKEN PAYOUT FUNCTIONS (INDIVIDUAL) // // ---------------------------------------- // /** @notice Allows to mint all the tokens * from investor and referrer perspectives * @dev can be called after forwardLiquidity() */ function getMyTokens(/*💰*/) external afterUniswapTransfer { payoutInvestorAddress(msg.sender); payoutReferralAddress(msg.sender); } /** @notice Allows to mint tokens for specific investor address * @dev aggregades investors tokens across all investment days * and uses GRISE_CONTRACT instance to mint all the GRISE tokens * @param _investorAddress requested investor calculation address * @return _payout amount minted to the investors address */ function payoutInvestorAddress( address _investorAddress ) public afterUniswapTransfer returns (uint256 _payout) { for (uint8 i = 1; i <= INVESTMENT_DAYS; i++) { if (investorBalances[_investorAddress][i] > 0) { _payout += investorBalances[_investorAddress][i].mul( _calculateDailyRatio(i) ).div(100E18); investorBalances[_investorAddress][i] = 0; } } if (_payout > 0) { GRISE_CONTRACT.mintSupply( _investorAddress, _payout ); } } /** @notice Allows to mint tokens for specific referrer address * @dev must be pre-calculated in prepareReferralBonuses() * @param _referralAddress referrer payout address * @return _referralTokens amount minted to the referrer address */ function payoutReferralAddress( address _referralAddress ) public afterUniswapTransfer returns (uint256 _referralTokens) { _referralTokens = referralTokens[_referralAddress]; if (referralTokens[_referralAddress] > 0) { referralTokens[_referralAddress] = 0; GRISE_CONTRACT.mintSupply( _referralAddress, _referralTokens ); } } // GRISE TOKEN PAYOUT FUNCTIONS (BATCHES) // // ------------------------------------- // /** @notice Allows to mint tokens for specific investment day * recommended batch size is up to 50 addresses per call * @param _investmentDay processing investment day * @param _investorBatchFrom batch starting index * @param _investorBatchTo bach finishing index */ function payoutInvestmentDayBatch( uint256 _investmentDay, uint256 _investorBatchFrom, uint256 _investorBatchTo ) external afterUniswapTransfer onlyFundedDays(_investmentDay) { require( _investorBatchFrom < _investorBatchTo, 'GRISE: incorrect investment batch' ); uint256 _dailyRatio = _calculateDailyRatio(_investmentDay); for (uint256 i = _investorBatchFrom; i < _investorBatchTo; i++) { address _investor = investorAccounts[_investmentDay][i]; uint256 _balance = investorBalances[_investor][_investmentDay]; uint256 _payout = _balance.mul(_dailyRatio).div(100E18); if (investorBalances[_investor][_investmentDay] > 0) { investorBalances[_investor][_investmentDay] = 0; GRISE_CONTRACT.mintSupply( _investor, _payout ); } } } /** @notice Allows to mint tokens for referrers in batches * @dev can be called right after forwardLiquidity() * recommended batch size is up to 50 addresses per call * @param _referralBatchFrom batch starting index * @param _referralBatchTo bach finishing index */ function payoutReferralBatch( uint256 _referralBatchFrom, uint256 _referralBatchTo ) external afterUniswapTransfer { require( _referralBatchFrom < _referralBatchTo, 'GRISE: incorrect referral batch' ); for (uint256 i = _referralBatchFrom; i < _referralBatchTo; i++) { address _referralAddress = referralAccounts[i]; uint256 _referralTokens = referralTokens[_referralAddress]; if (referralTokens[_referralAddress] > 0) { referralTokens[_referralAddress] = 0; GRISE_CONTRACT.mintSupply( _referralAddress, _referralTokens ); } } } // INFO VIEW FUNCTIONS (PERSONAL) // // ------------------------------ // /** @notice checks for callers investment amount on specific day (with bonus) * @return total amount invested across specific investment day (with bonus) */ function myInvestmentAmount(uint256 _investmentDay) external view returns (uint256) { return investorBalances[msg.sender][_investmentDay]; } /** @notice checks for callers claimable amount on specific day (with bonus) * @return total amount claimable across specific investment day (with bonus) */ function myClaimAmount(uint256 _investmentDay) external view returns (uint256) { if (investorBalances[msg.sender][_investmentDay] > 0) { return investorBalances[msg.sender][_investmentDay].mul( _calculateDailyRatio(_investmentDay)).div(100E18); }else{ return 0; } } /** @notice checks for callers investment amount on each day (with bonus) * @return _myAllDays total amount invested across all days (with bonus) */ function myInvestmentAmountAllDays() external view returns (uint256[51] memory _myAllDays) { for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) { _myAllDays[i] = investorBalances[msg.sender][i]; } } /** @notice checks for callers total investment amount (with bonus) * @return total amount invested across all investment days (with bonus) */ function myTotalInvestmentAmount() external view returns (uint256) { return investorTotalBalance[msg.sender]; } /** @notice checks for callers total claimable amount (with refferal bonus) * @return total claimable amount across all investment days (with refferal bonus) */ function myClaimAmountAllDays() external view returns (uint256) { uint256 _payout; for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) { if (investorBalances[msg.sender][i] > 0) { _payout += investorBalances[msg.sender][i].mul( _calculateDailyRatio(i) ).div(100E18); } } return _payout + referralTokens[msg.sender]; } // INFO VIEW FUNCTIONS (GLOBAL) // // ---------------------------- // /** @notice checks for investors count on specific day * @return investors count for specific day */ function investorsOnDay(uint256 _investmentDay) public view returns (uint256) { return dailyTotalInvestment[_investmentDay] > 0 ? investorAccountCount[_investmentDay] : 0; } /** @notice checks for investors count on each day * @return _allInvestors array with investors count for each day */ function investorsOnAllDays() external view returns (uint256[51] memory _allInvestors) { for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) { _allInvestors[i] = investorsOnDay(i); } } /** @notice checks for investment amount on each day * @return _allInvestments array with investment amount for each day */ function investmentsOnAllDays() external view returns (uint256[51] memory _allInvestments) { for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) { _allInvestments[i] = dailyTotalInvestment[i]; } } /** @notice checks for supply amount on each day * @return _allSupply array with supply amount for each day */ function supplyOnAllDays() external view returns (uint256[51] memory _allSupply) { for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) { _allSupply[i] = dailyTotalSupply[i]; } } // HELPER FUNCTIONS (PURE) // // ----------------------- // /** @notice checks that provided days are valid for investemnt * @dev used in reserveGrise() and reserveGriseWithToken() */ function checkInvestmentDays( uint8[] memory _investmentDays, uint64 _griseDay, address _senderAddress, uint256 _senderValue ) internal { uint256 _totalDays = _investmentDays.length; uint256 _dailyAmount = _senderValue.div(_totalDays); for (uint8 _i = 0; _i < _investmentDays.length; _i++) { require( (_dailyAmount >= MIN_INVEST) || (investorBalances[_senderAddress][_investmentDays[_i]] > 0), 'GRISE: investment below minimum' ); require( _investmentDays[_i] >= _griseDay, 'GRISE: investment day already passed' ); require( _investmentDays[_i] > 0 && _investmentDays[_i] <= INVESTMENT_DAYS, 'GRISE: incorrect investment day' ); require( (dailySlots[_investmentDays[_i]] < MAX_DAY_SLOT) || (investorBalances[_senderAddress][_investmentDays[_i]] > 0) , 'GRISE: investment slots are not available' ); if(investorBalances[_senderAddress][_investmentDays[_i]] == 0){ dailySlots[_investmentDays[_i]]++; } } } /** @notice prepares path variable for uniswap to exchange tokens * @dev used in reserveGriseWithToken() swapExactTokensForETH call * @param _tokenAddress ERC20 token address to be swapped for ETH * @return _path that is used to swap tokens for ETH on uniswap */ function preparePath( address _tokenAddress ) internal pure returns ( address[] memory _path ) { _path = new address[](2); _path[0] = _tokenAddress; _path[1] = WETH; } /** @notice keeps team contribution * @dev subtracts amount during forwardLiquidity() * @return ETH amount the team is allowed to withdraw */ function _teamContribution( uint256 _teamAmount ) internal returns (uint256) { TEAM_ETHER = _teamAmount; return _teamAmount; } /** @notice checks for invesments on all days * @dev used in forwardLiquidity() requirements * @return $fundedDays - amount of funded days 0-50 */ function fundedDays() public view returns ( uint8 $fundedDays ) { for (uint8 i = 1; i <= INVESTMENT_DAYS; i++) { if (dailyTotalInvestment[i] > 0) $fundedDays++; } } /** @notice GRISE equivalent in ETH price calculation * @dev returned value has 100E18 precision - divided later on * @return token price for specific day based on total investement */ function _calculateDailyRatio( uint256 _investmentDay ) internal view returns (uint256) { uint256 dailyRatio = dailyTotalSupply[_investmentDay].mul(100E18) .div(dailyTotalInvestment[_investmentDay]); uint256 remainderCheck = dailyTotalSupply[_investmentDay].mul(100E18) .mod(dailyTotalInvestment[_investmentDay]); return remainderCheck == 0 ? dailyRatio : dailyRatio.add(1); } // TIMING FUNCTIONS // // ---------------- // /** @notice shows current slot of GriseToken * @dev value is fetched from GRISE_CONTRACT * @return iteration day since GRISE inception */ function _currentLPDay() public view returns (uint64) { return GRISE_CONTRACT.currentLPDay(); } /** @notice allows to withdraw team funds for the work * strictly only after the uniswap liquidity is formed */ function requestTeamFunds() external afterUniswapTransfer { TEAM_ADDRESS.transfer(TEAM_ETHER.mul(4).div(5)); DEV_ADDRESS.transfer(TEAM_ETHER.div(5)); } function notContract(address _addr) internal view returns (bool) { uint32 size; assembly { size := extcodesize(_addr) } return (size == 0); } } library SafeMathLT { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'GRISE: addition overflow'); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'GRISE: subtraction overflow'); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'GRISE: multiplication overflow'); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, 'GRISE: division by zero'); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'GRISE: modulo by zero'); return a % b; } }
checks that provided days are valid for investemnt used in reserveGrise() and reserveGriseWithToken()/
function checkInvestmentDays( uint8[] memory _investmentDays, uint64 _griseDay, address _senderAddress, uint256 _senderValue ) internal { uint256 _totalDays = _investmentDays.length; uint256 _dailyAmount = _senderValue.div(_totalDays); for (uint8 _i = 0; _i < _investmentDays.length; _i++) { require( (_dailyAmount >= MIN_INVEST) || (investorBalances[_senderAddress][_investmentDays[_i]] > 0), 'GRISE: investment below minimum' ); require( _investmentDays[_i] >= _griseDay, 'GRISE: investment day already passed' ); require( _investmentDays[_i] > 0 && _investmentDays[_i] <= INVESTMENT_DAYS, 'GRISE: incorrect investment day' ); require( (dailySlots[_investmentDays[_i]] < MAX_DAY_SLOT) || (investorBalances[_senderAddress][_investmentDays[_i]] > 0) , 'GRISE: investment slots are not available' ); if(investorBalances[_senderAddress][_investmentDays[_i]] == 0){ dailySlots[_investmentDays[_i]]++; } } }
1,197,613
pragma solidity ^0.4.24; import '../../tokens/ERC677TokenContract.sol'; /** * @title Deed to hold RIF tokens in exchange for ownership of a node * * @dev The deed can be controlled only by the registrar and can only send tokens back to the owner. */ contract TokenDeed { address constant RESOURCE_POOL_ADDRESS = 0xe594df49aa7a13ccdd2db3a7917312e02374f744; uint constant RENT_PAYMENT_TIME = 3 * 30 days; // 3 months uint constant VALIDITY = 365 days; // 1 year address public registrar; address public owner; address public previousOwner; uint public creationDate; uint public expirationDate; uint public tokenQuantity; ERC677TokenContract public tokenContract; bool active; event OwnerChanged(address newOwner); event DeedClosed(); modifier onlyRegistrar { require(msg.sender == registrar); _; } modifier onlyActive { require(active); _; } /** * @dev Constructor for a TokenDeed * * @param _owner The deed's owner * @param _tokenQuantity Amount of tokens locked in the Deed * @param _tokenContract Address of the contract which handles tokens **/ constructor(address _owner, uint _tokenQuantity, ERC677TokenContract _tokenContract) public { owner = _owner; registrar = msg.sender; creationDate = now; expirationDate = 0; active = true; tokenQuantity = _tokenQuantity; tokenContract = _tokenContract; } function setOwner(address newOwner) public onlyRegistrar { require(newOwner != 0); previousOwner = owner; // This allows contracts to check who sent them the ownership owner = newOwner; emit OwnerChanged(newOwner); } function setRegistrar(address newRegistrar) public onlyRegistrar { registrar = newRegistrar; } /** * @dev Sets the Deed's new balance, returning the difference to the owner * * The new balance MUST be lower or equal than the current one * * @param newTokenQuantity The new balance in tokens * @param throwOnFailure Flag to indicate if the token transference should throw or not **/ function setBalance(uint newTokenQuantity, bool throwOnFailure) public onlyRegistrar onlyActive { // Check if it has enough balance to set the value require(tokenQuantity >= newTokenQuantity); uint diffTokenQuantity = tokenQuantity - newTokenQuantity; tokenQuantity = newTokenQuantity; // Send the difference to the owner require(tokenContract.transfer(owner, diffTokenQuantity) || !throwOnFailure); } /** * @dev Computes and sets the expirationDate from a given date, starting the vigency period * * @param startDate Date to calculate the expirationDate from * @param rentValue The value of the initial rent fee to pay in tokens **/ function startExpiration(uint startDate, uint rentValue) public onlyRegistrar onlyActive { require(expirationDate == 0 && startDate <= now); // require expiration hasn't started require(rentValue <= tokenQuantity); expirationDate = startDate + VALIDITY; // transfer the fee to the resource pool address tokenQuantity = tokenQuantity - rentValue; require(tokenContract.transfer(RESOURCE_POOL_ADDRESS, rentValue)); } /** * @dev Pay the Deed's rent, thus extending the expirationDate and the vigency period * * Can only be called when the current date falls within the payment period (3 months) * * @param rentValue The value to pay in tokens **/ function payRent(uint rentValue) public onlyRegistrar onlyActive returns(bool) { require(canPayRent()); require(tokenContract.transfer(RESOURCE_POOL_ADDRESS, rentValue)); expirationDate = expirationDate + VALIDITY; return true; } /** * @dev Returns wheter the current date falls within the Deed's rent payment period **/ function canPayRent() public view returns(bool) { return expirationDate - RENT_PAYMENT_TIME <= now && now <= expirationDate; } /** * @dev Returns wether the Deed is expired or not **/ function expired() public view returns(bool) { return 0 < expirationDate && expirationDate < now; } /** * @dev Close a deed and refund a specified fraction of the bid value * * @param refundRatio The amount*1/1000 to refund in tokens */ function closeDeed(uint refundRatio) public onlyRegistrar onlyActive { refundAndDestroy(refundRatio); } /** * @dev Close an expired deed. No funds are returned **/ function closeExpiredDeed() public onlyActive { require(expired(), "Deed should be expired"); refundAndDestroy(0); } /** * @dev Internal method which handles fund returns/burning and the Deed's destruction * * @param refundRatio The amount*1/1000 to refund in tokens **/ function refundAndDestroy(uint refundRatio) private onlyActive { require(refundRatio <= 1000); active = false; uint torefund = (1000 - refundRatio) * tokenQuantity / 1000; require(tokenContract.transfer(RESOURCE_POOL_ADDRESS, torefund)); tokenQuantity -= torefund; emit DeedClosed(); destroyDeed(); } /** * @dev Close a deed and refund a specified fraction of the bid value */ function destroyDeed() private { require(!active); if (tokenContract.transfer(owner, tokenQuantity)) { selfdestruct(RESOURCE_POOL_ADDRESS); } } function tokenFallback(address from, uint256 amount, bytes data) public returns (bool) { return true; } }
Returns wether the Deed is expired or not/
function expired() public view returns(bool) { return 0 < expirationDate && expirationDate < now; }
1,051,521
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {PermissionAdmin} from '@kyber.network/utils-sc/contracts/PermissionAdmin.sol'; import {IKyberGovernance} from '../interfaces/governance/IKyberGovernance.sol'; import {IExecutorWithTimelock} from '../interfaces/governance/IExecutorWithTimelock.sol'; import {IVotingPowerStrategy} from '../interfaces/governance/IVotingPowerStrategy.sol'; import {IProposalValidator} from '../interfaces/governance/IProposalValidator.sol'; import {getChainId} from '../misc/Helpers.sol'; /** * @title Kyber Governance contract for Kyber 3.0 * - Create a Proposal * - Cancel a Proposal * - Queue a Proposal * - Execute a Proposal * - Submit Vote to a Proposal * Proposal States : Pending => Active => Succeeded(/Failed/Finalized) * => Queued => Executed(/Expired) * The transition to "Canceled" can appear in multiple states **/ contract KyberGovernance is IKyberGovernance, PermissionAdmin { using SafeMath for uint256; bytes32 public constant DOMAIN_TYPEHASH = keccak256( 'EIP712Domain(string name,uint256 chainId,address verifyingContract)' ); bytes32 public constant VOTE_EMITTED_TYPEHASH = keccak256( 'VoteEmitted(uint256 id,uint256 optionBitMask)' ); string public constant NAME = 'Kyber Governance'; address private _daoOperator; uint256 private _proposalsCount; mapping(uint256 => Proposal) private _proposals; mapping(address => bool) private _authorizedExecutors; mapping(address => bool) private _authorizedVotingPowerStrategies; constructor( address admin, address daoOperator, address[] memory executors, address[] memory votingPowerStrategies ) PermissionAdmin(admin) { require(daoOperator != address(0), 'invalid dao operator'); _daoOperator = daoOperator; _authorizeExecutors(executors); _authorizeVotingPowerStrategies(votingPowerStrategies); } /** * @dev Creates a Binary Proposal (needs to be validated by the Proposal Validator) * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param executionParams data for execution, includes * targets list of contracts called by proposal's associated transactions * weiValues list of value in wei for each proposal's associated transaction * signatures list of function signatures (can be empty) to be used when created the callData * calldatas list of calldatas: if associated signature empty, * calldata ready, else calldata is arguments * withDelegatecalls boolean, true = transaction delegatecalls the taget, * else calls the target * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createBinaryProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, BinaryProposalParams memory executionParams, uint256 startTime, uint256 endTime, string memory link ) external override returns (uint256 proposalId) { require(executionParams.targets.length != 0, 'create binary invalid empty targets'); require( executionParams.targets.length == executionParams.weiValues.length && executionParams.targets.length == executionParams.signatures.length && executionParams.targets.length == executionParams.calldatas.length && executionParams.targets.length == executionParams.withDelegatecalls.length, 'create binary inconsistent params length' ); require(isExecutorAuthorized(address(executor)), 'create binary executor not authorized'); require( isVotingPowerStrategyAuthorized(address(strategy)), 'create binary strategy not authorized' ); proposalId = _proposalsCount; require( IProposalValidator(address(executor)).validateBinaryProposalCreation( strategy, msg.sender, startTime, endTime, _daoOperator ), 'validate proposal creation invalid' ); ProposalWithoutVote storage newProposalData = _proposals[proposalId].proposalData; newProposalData.id = proposalId; newProposalData.proposalType = ProposalType.Binary; newProposalData.creator = msg.sender; newProposalData.executor = executor; newProposalData.targets = executionParams.targets; newProposalData.weiValues = executionParams.weiValues; newProposalData.signatures = executionParams.signatures; newProposalData.calldatas = executionParams.calldatas; newProposalData.withDelegatecalls = executionParams.withDelegatecalls; newProposalData.startTime = startTime; newProposalData.endTime = endTime; newProposalData.strategy = strategy; newProposalData.link = link; // only 2 options, YES and NO newProposalData.options.push('YES'); newProposalData.options.push('NO'); newProposalData.voteCounts.push(0); newProposalData.voteCounts.push(0); // use max voting power to finalise the proposal newProposalData.maxVotingPower = strategy.getMaxVotingPower(); _proposalsCount++; // call strategy to record data if needed strategy.handleProposalCreation(proposalId, startTime, endTime); emit BinaryProposalCreated( proposalId, msg.sender, executor, strategy, executionParams.targets, executionParams.weiValues, executionParams.signatures, executionParams.calldatas, executionParams.withDelegatecalls, startTime, endTime, link, newProposalData.maxVotingPower ); } /** * @dev Creates a Generic Proposal (needs to be validated by the Proposal Validator) * It only gets the winning option without any executions * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param options list of options to vote for * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createGenericProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, string[] memory options, uint256 startTime, uint256 endTime, string memory link ) external override returns (uint256 proposalId) { require( isExecutorAuthorized(address(executor)), 'create generic executor not authorized' ); require( isVotingPowerStrategyAuthorized(address(strategy)), 'create generic strategy not authorized' ); proposalId = _proposalsCount; require( IProposalValidator(address(executor)).validateGenericProposalCreation( strategy, msg.sender, startTime, endTime, options, _daoOperator ), 'validate proposal creation invalid' ); Proposal storage newProposal = _proposals[proposalId]; ProposalWithoutVote storage newProposalData = newProposal.proposalData; newProposalData.id = proposalId; newProposalData.proposalType = ProposalType.Generic; newProposalData.creator = msg.sender; newProposalData.executor = executor; newProposalData.startTime = startTime; newProposalData.endTime = endTime; newProposalData.strategy = strategy; newProposalData.link = link; newProposalData.options = options; newProposalData.voteCounts = new uint256[](options.length); // use max voting power to finalise the proposal newProposalData.maxVotingPower = strategy.getMaxVotingPower(); _proposalsCount++; // call strategy to record data if needed strategy.handleProposalCreation(proposalId, startTime, endTime); emit GenericProposalCreated( proposalId, msg.sender, executor, strategy, options, startTime, endTime, link, newProposalData.maxVotingPower ); } /** * @dev Cancels a Proposal. * - Callable by the _daoOperator with relaxed conditions, * or by anybody if the conditions of cancellation on the executor are fulfilled * @param proposalId id of the proposal **/ function cancel(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalState state = getProposalState(proposalId); require( state != ProposalState.Executed && state != ProposalState.Canceled && state != ProposalState.Expired && state != ProposalState.Finalized, 'invalid state to cancel' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; require( msg.sender == _daoOperator || IProposalValidator(address(proposal.executor)).validateProposalCancellation( IKyberGovernance(this), proposalId, proposal.creator ), 'validate proposal cancellation failed' ); proposal.canceled = true; if (proposal.proposalType == ProposalType.Binary) { for (uint256 i = 0; i < proposal.targets.length; i++) { proposal.executor.cancelTransaction( proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], proposal.executionTime, proposal.withDelegatecalls[i] ); } } // notify voting power strategy about the cancellation proposal.strategy.handleProposalCancellation(proposalId); emit ProposalCanceled(proposalId); } /** * @dev Queue the proposal (If Proposal Succeeded), only for Binary proposals * @param proposalId id of the proposal to queue **/ function queue(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); require( getProposalState(proposalId) == ProposalState.Succeeded, 'invalid state to queue' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; // generic proposal does not have Succeeded state assert(proposal.proposalType == ProposalType.Binary); uint256 executionTime = block.timestamp.add(proposal.executor.getDelay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.executor, proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], executionTime, proposal.withDelegatecalls[i] ); } proposal.executionTime = executionTime; emit ProposalQueued(proposalId, executionTime, msg.sender); } /** * @dev Execute the proposal (If Proposal Queued), only for Binary proposals * @param proposalId id of the proposal to execute **/ function execute(uint256 proposalId) external override payable { require(proposalId < _proposalsCount, 'invalid proposal id'); require(getProposalState(proposalId) == ProposalState.Queued, 'only queued proposals'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; // generic proposal does not have Queued state assert(proposal.proposalType == ProposalType.Binary); proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { proposal.executor.executeTransaction{value: proposal.weiValues[i]}( proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], proposal.executionTime, proposal.withDelegatecalls[i] ); } emit ProposalExecuted(proposalId, msg.sender); } /** * @dev Function allowing msg.sender to vote for/against a proposal * @param proposalId id of the proposal * @param optionBitMask bitmask optionBitMask of voter * for Binary Proposal, optionBitMask should be either 1 or 2 (Accept/Reject) * for Generic Proposal, optionBitMask is the bitmask of voted options **/ function submitVote(uint256 proposalId, uint256 optionBitMask) external override { return _submitVote(msg.sender, proposalId, optionBitMask); } /** * @dev Function to register the vote of user that has voted offchain via signature * @param proposalId id of the proposal * @param optionBitMask the bit mask of voted options * @param v v part of the voter signature * @param r r part of the voter signature * @param s s part of the voter signature **/ function submitVoteBySignature( uint256 proposalId, uint256 optionBitMask, uint8 v, bytes32 r, bytes32 s ) external override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(NAME)), getChainId(), address(this)) ), keccak256(abi.encode(VOTE_EMITTED_TYPEHASH, proposalId, optionBitMask)) ) ); address signer = ecrecover(digest, v, r, s); require(signer != address(0), 'invalid signature'); return _submitVote(signer, proposalId, optionBitMask); } /** * @dev Function to handle voting power changed for a voter * caller must be the voting power strategy of the proposal * @param voter address that has changed the voting power * @param newVotingPower new voting power of that address, * old voting power can be taken from records * @param proposalIds list proposal ids that belongs to this voting power strategy * should update the voteCound of the active proposals in the list **/ function handleVotingPowerChanged( address voter, uint256 newVotingPower, uint256[] calldata proposalIds ) external override { uint224 safeNewVotingPower = _safeUint224(newVotingPower); for (uint256 i = 0; i < proposalIds.length; i++) { // only update for active proposals if (getProposalState(proposalIds[i]) != ProposalState.Active) continue; ProposalWithoutVote storage proposal = _proposals[proposalIds[i]].proposalData; require(address(proposal.strategy) == msg.sender, 'invalid voting power strategy'); Vote memory vote = _proposals[proposalIds[i]].votes[voter]; if (vote.optionBitMask == 0) continue; // not voted yet uint256 oldVotingPower = uint256(vote.votingPower); // update totalVotes of the proposal proposal.totalVotes = proposal.totalVotes.add(newVotingPower).sub(oldVotingPower); for (uint256 j = 0; j < proposal.options.length; j++) { if (vote.optionBitMask & (2**j) == 2**j) { // update voteCounts for each voted option proposal.voteCounts[j] = proposal.voteCounts[j].add(newVotingPower).sub(oldVotingPower); } } // update voting power of the voter _proposals[proposalIds[i]].votes[voter].votingPower = safeNewVotingPower; emit VotingPowerChanged( proposalIds[i], voter, vote.optionBitMask, vote.votingPower, safeNewVotingPower ); } } /** * @dev Transfer dao operator * @param newDaoOperator new dao operator **/ function transferDaoOperator(address newDaoOperator) external { require(msg.sender == _daoOperator, 'only dao operator'); require(newDaoOperator != address(0), 'invalid dao operator'); _daoOperator = newDaoOperator; emit DaoOperatorTransferred(newDaoOperator); } /** * @dev Add new addresses to the list of authorized executors * @param executors list of new addresses to be authorized executors **/ function authorizeExecutors(address[] memory executors) public override onlyAdmin { _authorizeExecutors(executors); } /** * @dev Remove addresses to the list of authorized executors * @param executors list of addresses to be removed as authorized executors **/ function unauthorizeExecutors(address[] memory executors) public override onlyAdmin { _unauthorizeExecutors(executors); } /** * @dev Add new addresses to the list of authorized strategies * @param strategies list of new addresses to be authorized strategies **/ function authorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _authorizeVotingPowerStrategies(strategies); } /** * @dev Remove addresses to the list of authorized strategies * @param strategies list of addresses to be removed as authorized strategies **/ function unauthorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _unauthorizedVotingPowerStrategies(strategies); } /** * @dev Returns whether an address is an authorized executor * @param executor address to evaluate as authorized executor * @return true if authorized **/ function isExecutorAuthorized(address executor) public override view returns (bool) { return _authorizedExecutors[executor]; } /** * @dev Returns whether an address is an authorized strategy * @param strategy address to evaluate as authorized strategy * @return true if authorized **/ function isVotingPowerStrategyAuthorized(address strategy) public override view returns (bool) { return _authorizedVotingPowerStrategies[strategy]; } /** * @dev Getter the address of the daoOperator, that can mainly cancel proposals * @return The address of the daoOperator **/ function getDaoOperator() external override view returns (address) { return _daoOperator; } /** * @dev Getter of the proposal count (the current number of proposals ever created) * @return the proposal count **/ function getProposalsCount() external override view returns (uint256) { return _proposalsCount; } /** * @dev Getter of a proposal by id * @param proposalId id of the proposal to get * @return the proposal as ProposalWithoutVote memory object **/ function getProposalById(uint256 proposalId) external override view returns (ProposalWithoutVote memory) { return _proposals[proposalId].proposalData; } /** * @dev Getter of the vote data of a proposal by id * including totalVotes, voteCounts and options * @param proposalId id of the proposal * @return (totalVotes, voteCounts, options) **/ function getProposalVoteDataById(uint256 proposalId) external override view returns ( uint256, uint256[] memory, string[] memory ) { ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; return (proposal.totalVotes, proposal.voteCounts, proposal.options); } /** * @dev Getter of the Vote of a voter about a proposal * Note: Vote is a struct: ({uint32 bitOptionMask, uint224 votingPower}) * @param proposalId id of the proposal * @param voter address of the voter * @return The associated Vote memory object **/ function getVoteOnProposal(uint256 proposalId, address voter) external override view returns (Vote memory) { return _proposals[proposalId].votes[voter]; } /** * @dev Get the current state of a proposal * @param proposalId id of the proposal * @return The current state if the proposal **/ function getProposalState(uint256 proposalId) public override view returns (ProposalState) { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp < proposal.startTime) { return ProposalState.Pending; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.proposalType == ProposalType.Generic) { return ProposalState.Finalized; } else if ( !IProposalValidator(address(proposal.executor)).isBinaryProposalPassed( IKyberGovernance(this), proposalId ) ) { return ProposalState.Failed; } else if (proposal.executionTime == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (proposal.executor.isProposalOverGracePeriod(this, proposalId)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _queueOrRevert( IExecutorWithTimelock executor, address target, uint256 value, string memory signature, bytes memory callData, uint256 executionTime, bool withDelegatecall ) internal { require( !executor.isActionQueued( keccak256(abi.encode(target, value, signature, callData, executionTime, withDelegatecall)) ), 'duplicated action' ); executor.queueTransaction(target, value, signature, callData, executionTime, withDelegatecall); } function _submitVote( address voter, uint256 proposalId, uint256 optionBitMask ) internal { require(proposalId < _proposalsCount, 'invalid proposal id'); require(getProposalState(proposalId) == ProposalState.Active, 'voting closed'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; uint256 numOptions = proposal.options.length; if (proposal.proposalType == ProposalType.Binary) { // either Yes (1) or No (2) require(optionBitMask == 1 || optionBitMask == 2, 'wrong vote for binary proposal'); } else { require( optionBitMask > 0 && optionBitMask < 2**numOptions, 'invalid options for generic proposal' ); } Vote memory vote = _proposals[proposalId].votes[voter]; uint256 votingPower = proposal.strategy.handleVote(voter, proposalId, optionBitMask); if (vote.optionBitMask == 0) { // first time vote, increase the totalVotes of the proposal proposal.totalVotes = proposal.totalVotes.add(votingPower); } for (uint256 i = 0; i < proposal.options.length; i++) { bool hasVoted = (vote.optionBitMask & (2**i)) == 2**i; bool isVoting = (optionBitMask & (2**i)) == 2**i; if (hasVoted && !isVoting) { proposal.voteCounts[i] = proposal.voteCounts[i].sub(votingPower); } else if (!hasVoted && isVoting) { proposal.voteCounts[i] = proposal.voteCounts[i].add(votingPower); } } _proposals[proposalId].votes[voter] = Vote({ optionBitMask: _safeUint32(optionBitMask), votingPower: _safeUint224(votingPower) }); emit VoteEmitted(proposalId, voter, _safeUint32(optionBitMask), _safeUint224(votingPower)); } function _authorizeExecutors(address[] memory executors) internal { for(uint256 i = 0; i < executors.length; i++) { _authorizedExecutors[executors[i]] = true; emit ExecutorAuthorized(executors[i]); } } function _unauthorizeExecutors(address[] memory executors) internal { for(uint256 i = 0; i < executors.length; i++) { _authorizedExecutors[executors[i]] = false; emit ExecutorUnauthorized(executors[i]); } } function _authorizeVotingPowerStrategies(address[] memory strategies) internal { for(uint256 i = 0; i < strategies.length; i++) { _authorizedVotingPowerStrategies[strategies[i]] = true; emit VotingPowerStrategyAuthorized(strategies[i]); } } function _unauthorizedVotingPowerStrategies(address[] memory strategies) internal { for(uint256 i = 0; i < strategies.length; i++) { _authorizedVotingPowerStrategies[strategies[i]] = false; emit VotingPowerStrategyUnauthorized(strategies[i]); } } function _safeUint224(uint256 value) internal pure returns (uint224) { require(value < 2**224 - 1, 'value is too big (uint224)'); return uint224(value); } function _safeUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32 - 1, 'value is too big (uint32)'); return uint32(value); } }
Remove addresses to the list of authorized strategies strategies list of addresses to be removed as authorized strategies/
function unauthorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _unauthorizedVotingPowerStrategies(strategies); }
5,428,156
pragma solidity >0.5.0; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; // uint public MAX_AUTO_REGISTERED_AIRLINES = 4; uint public INSURANCE_STATUS_UNKNOWN = 0; uint public INSURANCE_STATUS_IN_PROGRESS = 1; uint public INSURANCE_STATUS_PAID = 1; uint public INSURANCE_STATUS_CLOSED = 2; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping (address=>bool) private authorizedCallers; struct Airline { bool isExists; uint256 registeredNumber; bool needApprove; bool isFunded; Votes votes; uint256 minVotes; } struct Votes{ uint votersCount; mapping(address => bool) voters; } uint256 private airlinesCount = 0; mapping(address => Airline) private airlines; struct InsuranceInfo{ address passenger; uint256 value; uint status; } mapping(address => InsuranceInfo) private insurances; mapping(address => uint256) private passengerBalances; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; // airlines[contractOwner] = Airline(contractOwner, AirlineState.Paid, "First Airline", 0); // totalPaidAirlines++; } //fallback function function() external payable { } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAuthorizedCaller(address contractAddress) { require(authorizedCallers[contractAddress] == true, "Not Authorized Caller"); _; } modifier checkAirlineExists(address airlineAddress) { require(airlines[airlineAddress].isExists, "Airline does't exist"); _; } modifier checkAirlineApproved(address airlineAddress) { Airline memory airline = airlines[airlineAddress]; require((airline.needApprove == false) || (airline.votes.votersCount >= airline.minVotes), "Need approval from other Airlines"); _; } modifier checkAirlineFunds(address airlineAddress) { Airline memory airline = airlines[airlineAddress]; require(airline.isFunded != true, "Need funds"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } function authorizeCaller(address contractAddress) external requireContractOwner requireIsOperational { authorizedCallers[contractAddress] = true; } function getAirlineOperatingStatus(address account) external view requireIsOperational returns(bool){ return airlines[account].isFunded; } function getInsuredPassenger_amount(address airline) external view requireIsOperational returns(address, uint256){ return (insurances[airline].passenger,insurances[airline].value); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airlineAddress, bool approveNeeded ) external requireIsOperational { airlines[airlineAddress] = Airline({ isExists: true, registeredNumber: airlinesCount, needApprove: approveNeeded, votes: Votes(0), isFunded: false, minVotes: airlinesCount.add(1).div(2) }); airlinesCount = airlinesCount.add(1); } // /** // * @dev Add vote to airline, return needApprove flag // * Can only be called from FlightSuretyApp contract // * // */ // function voteAirline(address airlineAddress, address voterAddress) // external // checkAirlineExists(airlineAddress) // requireIsOperational // returns (bool) // { // require(airlines[airlineAddress].votes.voters[voterAddress] == false, "Airline already voted by this account"); // airlines[airlineAddress].votes.votersCount = airlines[airlineAddress].votes.votersCount.add(1); // airlines[airlineAddress].votes.voters[voterAddress] = true; // airlines[airlineAddress].needApprove = airlines[airlineAddress].votes.votersCount < airlines[airlineAddress].minVotes; // return airlines[airlineAddress].needApprove; // } /** * @dev Buy insurance for a flight * */ function buy (address airline) external requireIsOperational payable { insurances[airline] = InsuranceInfo({ passenger: msg.sender, value: msg.value, status: INSURANCE_STATUS_IN_PROGRESS }); } /** * @dev Credits payouts to insurees */ function creditInsurees (address airline, uint256 amount ) external requireIsOperational { InsuranceInfo memory insurance = insurances[airline]; // if (insurance.status == INSURANCE_STATUS_IN_PROGRESS) { // uint256 insurancePayoutValue = getInsurancePayoutValue(airline); // uint256 balance = passengerBalances[insurance.passenger]; // passengerBalances[insurance.passenger] = balance.add(insurancePayoutValue); passengerBalances[insurance.passenger] = amount; // insurance.status = INSURANCE_STATUS_PAID; // } } /** * @dev Set insurance closed status */ function closeInsurance(address airline) external view requireIsOperational{ InsuranceInfo memory insurance = insurances[airline]; if (insurance.status != INSURANCE_STATUS_UNKNOWN) { insurance.status = INSURANCE_STATUS_CLOSED; } } // function getInsurancePayoutValue(address airline) public view requireIsOperational returns(uint256){ // InsuranceInfo memory insurance = insurances[airline]; // uint256 insurancePayoutValue = insurance.value.div(2); // return insurancePayoutValue.add(insurance.value); // } function getPassengerBalance(address passengerAddress) public view requireIsOperational returns(uint256){ return passengerBalances[passengerAddress]; } /** * @dev Transfers eligible payout funds to insuree * */ function pay (address payable passengerAddress ) external requireIsOperational payable { uint256 balance = passengerBalances[passengerAddress]; require(address(this).balance > balance, 'Not enough contact balance'); passengerBalances[passengerAddress] = 0; passengerAddress.transfer(balance); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund (address airlineAddress ) external requireIsOperational() checkAirlineExists(airlineAddress) checkAirlineApproved(airlineAddress) payable { // require(msg.value == 10 ether,"Ether should be 10"); // require(!airlines[airlineAddress].isFunded, "Airline is already funded"); airlines[airlineAddress].isFunded = true; } // function getFlightKey // ( // address airline, // string memory flight, // uint256 timestamp // ) // internal // pure // returns(bytes32) // { // return keccak256(abi.encodePacked(airline, flight, timestamp)); // } function isAirline(address airlineAddress) public view requireIsOperational() returns (bool) { return airlines[airlineAddress].isExists; } function getAirline(address airlineAddress) public view requireIsOperational() returns (bool isExists, uint256 registeredNumber, bool needApprove, bool isFunded, uint256 votersCount, uint minVotes) { Airline memory airline = airlines[airlineAddress]; return ( airline.isExists, airline.registeredNumber, airline.needApprove, airline.isFunded, airline.votes.votersCount, airline.minVotes ); } function getAirlinesCount() public view returns (uint256) { return airlinesCount; } function getAirlineIsVoted(address airlineAddress, address voter) public view returns (bool) { return airlines[airlineAddress].votes.voters[voter]; } function getAirlineVotersCount(address airlineAddress) public view returns (uint) { return airlines[airlineAddress].votes.votersCount; } function getAirlineMinVotes(address airlineAddress) public view returns (uint) { return airlines[airlineAddress].minVotes; } function setAirlineInfo( address airlineAddress, uint votersCount, bool isVote, bool needApproved ) public { airlines[airlineAddress].votes.votersCount = votersCount; airlines[airlineAddress].votes.voters[msg.sender] = isVote; airlines[airlineAddress].needApprove = needApproved; } }
Transfers eligible payout funds to insuree/
function pay (address payable passengerAddress ) external requireIsOperational payable { uint256 balance = passengerBalances[passengerAddress]; require(address(this).balance > balance, 'Not enough contact balance'); passengerBalances[passengerAddress] = 0; passengerAddress.transfer(balance); }
995,725
./full_match/5/0x420944D3a71bbdF90E21b15983F2ff9dFB9c49B2/sources/contracts/Crowdfunding.sol
is everything okay creating the campaign
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns(uint256){ require(campaign.deadline < block.timestamp, "The deadline should be a date in the future"); campaign.owner =_owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image =_image; numberOfCampaigns++; }
11,627,021
./partial_match/1/0x869fb8A354a565F7576009A88F2e8b7159A20010/sources/LazyButts.sol
Toggle the allowlist active state. Can only be called by delegates./
function setAllowListActive(bool isAllowListActive_) external onlyDelegates { require(isAllowListActive != isAllowListActive_, "Allowlist already set"); isAllowListActive = isAllowListActive_; }
2,891,722
./full_match/288/0xaBB5c9fC0dA8622B5371B24Dc50503f4525d7216/sources/contracts/yieldBearing/FactoryToken.sol
delete controller _controller controller of this contract/
function deleteController(address _controller) public onlyOwner onlyContract(_controller) { require(controllers[_controller]); controllers[_controller] = false; }
7,104,520
// // MIT License // // Copyright (c) 2018 REGA Risk Sharing // // 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. // // Author: Sergei Sevriugin // Version: 0.0.1 // pragma solidity ^0.4.18; import './interfaces/IERC20Controller.sol'; import './interfaces/IERC20Adapter.sol'; /// ERC20 Adapter contract ERC20Adapter is IERC20Adapter { /// ERC20 Controller IERC20Controller public controller; /// ERC20 Standard string public standard = "Token 0.1"; /// ERC20 Token name string public name = ""; /// ERC20 Token symbol string public symbol = ""; /// ERC20 Token decimals uint8 public decimals = 0; /// ERC20 total supply /// @return total ERC20 supply function totalSupply() public view returns (uint256) { require(controller != address(0)); return controller.cTotalSupply(); } /// ERC20 balance /// @param _owner token owner /// @return token owner balance function balanceOf(address _owner) public view returns (uint256) { require(controller != address(0)); require(_owner != address(0)); return controller.cBalanceOf(_owner); } /// ERC20 allowance /// @param _owner token owner /// @param _spender spender address /// @return allowance amount function allowance(address _owner, address _spender) public view returns (uint256) { require(controller != address(0)); require(_owner != address(0)); require(_spender != address(0)); return controller.cAllowance(_owner, _spender); } /// ERC20 transfer /// @param _to adress to transfer /// @param _value transfer amount /// @return TRUE if transfer is succesuful function transfer(address _to, uint256 _value) public returns (bool success) { require(controller != address(0)); require(_to != address(0)); require(_value != uint256(0)); return controller.cTransfer(_to, _value); } /// ERC20 transfer from /// @param _from address to transfer from /// @param _to adress to transfer to /// @param _value transfer amount /// @return TRUE if transfer is succesuful function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(controller != address(0)); require(_to != address(0)); require(_from != address(0)); require(_value != uint256(0)); return controller.cTransferFrom(_from, _to, _value); } /// ERC20 transfer approve /// @param _spender address to approve /// @param _value amount to approve /// @return TRUE if transfer is succesuful function approve(address _spender, uint256 _value) public returns (bool success) { require(controller != address(0)); require(_spender != address(0)); require(_value != uint256(0)); return controller.cApprove(_spender, _value); } /// ERC20 / ERC721 transfer approve /// @param _fromId NFT token ID to send value /// @param _spender address to approve /// @param _toId NFT token to recieve value /// @param _value amount to approve /// @return TRUE if transfer is succesuful function approveFrom(uint256 _fromId, address _spender, uint256 _toId, uint256 _value) public returns (bool success) { require(controller != address(0)); require(_fromId != uint256(0)); require(_spender != address(0)); require(_toId != uint256(0)); require(_value != uint256(0)); require(_fromId != _toId); return controller.cApproveFrom(_fromId, _spender, _toId, _value); } /// Constructor /// @param _controller ERC20 Controller /// @param _name ERC20 token name /// @param _symbol ERC20 token symbol /// @param _decimals ERC20 token decimals function ERC20Adapter(IERC20Controller _controller, string _name, string _symbol, uint8 _decimals) public { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input name = _name; symbol = _symbol; decimals = _decimals; controller = _controller; } }
ERC20 Controller ERC20 Standard ERC20 Token name ERC20 Token symbol ERC20 Token decimals ERC20 total supply return total ERC20 supply
function totalSupply() public view returns (uint256) { require(controller != address(0)); return controller.cTotalSupply(); }
12,939,580
./partial_match/1/0x476EBFDB3b00c63EACE11cbE699639e737605936/sources/IToken.sol
IERC20 specification. hard including it to avoid compatibility of openzeppelin with different libraries
interface IToken { 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); event Mint(address indexed minter,uint256 tokenAmount,uint256 assetAmount,uint256 price); event Burn(address indexed burner,uint256 tokenAmount,uint256 assetAmount,uint256 price); event FlashBorrow(address borrower,address target,address loanToken,uint256 loanAmount); function tokenPrice() external view returns (uint256); function mint(address receiver, uint256 depositAmount) external returns (uint256); function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); function flashBorrow( uint256 borrowAmount, address borrower, address target, string calldata signature, bytes calldata data ) external payable returns (bytes memory); function borrow( uint256 withdrawAmount, address borrower, address receiver, ) external payable returns (LoanOpenData memory); function marginTrade( uint256 leverageAmount, uint256 loanTokenSent, uint256 collateralTokenSent, address collateralTokenAddress, address trader, ) external payable returns (LoanOpenData memory); function profitOf(address user) external view returns (int256); function checkpointPrice(address _user) external view returns (uint256); function borrowInterestRate() external view returns (uint256); function nextBorrowInterestRate(uint256 borrowAmount) external view returns (uint256); function supplyInterestRate() external view returns (uint256); function nextSupplyInterestRate(int256 supplyAmount) external view returns (uint256); function totalSupplyInterestRate(uint256 assetSupply) external view returns (uint256); function totalAssetBorrow() external view returns (uint256); function totalAssetSupply() external view returns (uint256); function assetBalanceOf(address _owner) external view returns (uint256); function loanTokenAddress() external view returns (address); function initialPrice() external view returns (uint256); function loanParamsIds(uint256) external view returns (bytes32); function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); function revokeApproval(address _loanTokenAddress) external; function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; function DOMAIN_SEPARATOR() external view returns(bytes32); function PERMIT_TYPEHASH() external view returns(bytes32); function nonces(address) external view returns (uint); function setTarget(address _newTarget) external; function owner() external view returns (address); function transferOwnership(address newOwner) external; function initializeDomainSeparator() external; struct LoanOpenData { bytes32 loanId; uint256 principal; uint256 collateral; } }
9,136,819
pragma solidity ^0.6.7; import "./IndexToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./MeFiInterface.sol"; import "./IndexControllerStorage.sol"; // import "./UniIndexController.sol"; import "./MeFi.sol"; import "./IndexErc20.sol"; /** * @title MeFi Index Controller Contract * @author MeFi */ contract IndexControllerV1 is MeFiInterface, ExponentialNoError { // this should contain all the functions that MeFi will have as callable. bool public constant isController = true; address payable public admin; // Functions that should be callable from outside the function. function buyIndex(address _indexToken) external payable override returns (uint) { // should mint new tokens based on require(msg.value > 0); // This should be optimized so that calculateWeightedMarketCap doesn't make mulitple calls to the oracles. uint _tokenValue = IndexToken(_indexToken).tokenValue(); require(_tokenValue > 0); // FIXME uint256 amountToBeMinted = uint256(msg.value / _tokenValue); // Here I need to calculate the amount that needs to be minted. This possibly should be done somewhere else. // to avoid calling the oracle twice. require(mintAllowed(_indexToken, msg.sender, amountToBeMinted) == 0); //FIXME : make sure that I multiply properly so that fractional divison is possible. IndexErc20(_indexToken).mint(uint(msg.value / _tokenValue)); IndexErc20(_indexToken).transfer(msg.sender, msg.value / _tokenValue); } function redeemIndex(address indexToken) external override returns (uint) { return 0; } //Policy Hooks. Helper functions to determine if a certain action is allowed. function mintAllowed(address indexToken, address minter, uint mintAmount) public override returns (uint) { return 0; } function mintVerify(address _indexToken, address minter, uint mintAmount, uint mintTokens) external override returns (uint) { // Currently Unused. Will delete if no use is found. } function redeemAllowed(address indexToken, address redeemer, uint redeemTokens) external override returns (uint) { return 0; } function redeemVerify(address indexToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { } function isIndexController() public override returns (bool) { return true; } constructor () public { admin = msg.sender; } }
Currently Unused. Will delete if no use is found.
function mintVerify(address _indexToken, address minter, uint mintAmount, uint mintTokens) external override returns (uint) { }
15,832,327
./partial_match/42/0x44E6142545fbBc838D450F9Ab45eEf11aBbd94B2/sources/DfTokenizedDeposit.sol
price not less that price from oracle with 5% slippage
function getCompPriceInDAI() view public returns(uint256) { IPriceOracle compOracle = IComptroller(COMPTROLLER).oracle(); return compOracle.price("COMP") * 1e18 / compOracle.price("DAI") * 95 / 100; }
3,328,200
./full_match/4/0xAe3A60dF4E2e5663a72B85603D34AA9EEbFfFcDD/sources/browser/PublicPortal.sol
_stakeALT PRIVATE function is responsible for staking a token called from other functions. _xioQuantity, Amount of XIO token that needs to be staked. _tokensBought, Amount of bought tokens that is calculated from uniswap on the frontend. _days, Number of days of XIOs will be locked./
function _stakeALT( uint256 _xioQuantity, uint256 _tokensBought, uint256 _days ) private returns (uint256 bought) { uint256 soldXIO = calculateInterestRate(_xioQuantity, _days); address[] memory path; if (tokenB == WETH) { path = new address[](2); path[0] = XIO_CONTRACT; path[1] = WETH; path = new address[](3); path[0] = XIO_CONTRACT; path[1] = WETH; path[2] = tokenB; } uint256[] memory amounts = IUniswapV2Router02(uniswapV2Router) .swapExactTokensForTokens( soldXIO, _tokensBought, path, address(this), 1839591241 ); bought = amounts[amounts.length - 1]; uint256 _timestamp = block.timestamp; if (portalMemberData[_timestamp].stakerAddress != address(0)) { _timestamp = _timestamp.add(1); } portalMemberData[_timestamp] = PortalMember( msg.sender, tokenB, _xioQuantity, (_days).mul(ONE_DAY), bought ); }
12,325,059
./full_match/97/0x5377E9109C6d9420dE67a24b728035345A3E31F3/sources/_ankr.com/contracts/earn/LiquidTokenStakingPool.sol
reserve some gap for the future upgrades
{ IBearingToken internal _bearingToken; ICertificateToken internal _certificateToken; IEarnConfig internal _earnConfig; uint64 private minimumStake; uint64 private _minimumUnstake; uint256[50 - 5] private __reserved; pragma solidity ^0.8.7; modifier onlyGovernance() virtual { require( msg.sender == _earnConfig.getGovernanceAddress(), "LiquidTokenStakingPool: only governance allowed" ); _; } modifier onlyConsensus() virtual { require( msg.sender == _earnConfig.getConsensusAddress(), "LiquidTokenStakingPool: only consensus allowed" ); _; } modifier bondStakingUnpaused() virtual { require( !_earnConfig.isBondStakingPaused(), "LiquidTokenStakingPool: bond staking is paused" ); _; } function __LiquidTokenStakingPool_init( IEarnConfig earnConfig ) internal onlyInitializing { _earnConfig = earnConfig; } receive() external payable virtual { emit Received(msg.sender, msg.value); } function setBearingToken( address newValue ) external override onlyGovernance { address prevValue = address(_bearingToken); _bearingToken = IBearingToken(newValue); emit BearingTokenChanged(prevValue, newValue); } function setCertificateToken( address newValue ) external override onlyGovernance { address prevValue = address(_certificateToken); _certificateToken = ICertificateToken(newValue); emit CertificateTokenChanged(prevValue, newValue); } function setMinimumStake( uint256 newValue ) external virtual override onlyGovernance { require( newValue % 1 gwei == 0, "LiquidTokenStakingPool: value should be multiplied of gwei" ); uint256 prevValue = getMinStake(); minimumStake = uint64(newValue / 1 gwei); require( minimumStake * 1 gwei == newValue, "LiquidTokenStakingPool: overflow" ); emit MinimumStakeChanged(prevValue, newValue); } function setMinimumUnstake( uint256 newValue ) external virtual override onlyGovernance { require( newValue % 1 gwei == 0, "LiquidTokenStakingPool: value should be multiplied of gwei" ); uint256 prevValue = getMinUnstake(); _minimumUnstake = uint64(newValue / 1 gwei); require( _minimumUnstake * 1 gwei == newValue, "LiquidTokenStakingPool: overflow" ); emit MinimumUnstakeChanged(prevValue, newValue); } function getMinStake() public view virtual override returns (uint256) { return uint256(minimumStake) * 1 gwei; } function getMinUnstake() public view virtual override returns (uint256) { return uint256(_minimumUnstake) * 1 gwei; } function stakeBonds() external payable override nonReentrant bondStakingUnpaused { _stakeBonds(msg.sender, msg.value); } function stakeCerts() external payable override nonReentrant { _stakeCerts(msg.sender, msg.value); } function _stakeCerts(address staker, uint256 amount) internal { uint256 shares = _certificateToken.bondsToShares(amount); _stake(staker, amount, shares, false); _bearingToken.unlockSharesFor(staker, shares); _afterStake(staker, amount, shares); } function _stakeBonds(address staker, uint256 amount) internal { uint256 shares = _bearingToken.bondsToShares(amount); _stake(staker, amount, shares, true); _afterStake(staker, amount, shares); } function _stake( address staker, uint256 amount, uint256 shares, bool isRebasing ) internal { _beforeStake(staker, amount, shares); require( amount >= getMinStake(), "LiquidTokenStakingPool: value must be greater than min amount" ); require( amount % getMinStake() == 0, "LiquidTokenStakingPool: value must be multiple of min amount" ); _certificateToken.mint(address(_bearingToken), shares); _bearingToken.mint(staker, shares); emit Staked(staker, amount, shares, isRebasing); } ) internal virtual {} ) internal virtual {} function _beforeStake( address account, uint256 amount, uint256 shares function _afterStake( address account, uint256 amount, uint256 shares function _unstakeBondsFor( address receiverAddress, uint256 amount ) internal { require( amount >= getMinUnstake(), "LiquidTokenStakingPool: value must be greater than min amount" ); address ownerAddress = msg.sender; uint256 shares = _bearingToken.bondsToShares(amount); amount = _bearingToken.sharesToBonds(shares); require( _bearingToken.balanceOf(ownerAddress) >= amount, "LiquidTokenStakingPool: cannot unstake more than have on address" ); _beforeUnstake(ownerAddress, receiverAddress, amount); _certificateToken.burn(address(_bearingToken), shares); _bearingToken.burn(ownerAddress, shares); _afterUnstake(ownerAddress, receiverAddress, amount); emit Unstaked(ownerAddress, receiverAddress, amount, shares, true); } function _unstakeCertsFor( address receiverAddress, uint256 shares ) internal { address ownerAddress = msg.sender; uint256 amount = _certificateToken.sharesToBonds(shares); require( amount >= getMinUnstake(), "LiquidTokenStakingPool: value must be greater than min amount" ); shares = _certificateToken.bondsToShares(amount); require( _certificateToken.balanceOf(ownerAddress) >= shares, "LiquidTokenStakingPool: cannot unstake more than have on address" ); _beforeUnstake(ownerAddress, receiverAddress, amount); _certificateToken.burn(ownerAddress, shares); _afterUnstake(ownerAddress, receiverAddress, amount); emit Unstaked(ownerAddress, receiverAddress, amount, shares, false); } ) internal virtual {} ) internal virtual {} function _beforeUnstake( address ownerAddress, address receiverAddress, uint256 amount function _afterUnstake( address ownerAddress, address receiverAddress, uint256 amount function _unsafeTransfer( address receiverAddress, uint256 amount, bool limit ) internal virtual returns (bool) { address payable wallet = payable(receiverAddress); bool success; if (limit) { assembly { success := call(10000, wallet, amount, 0, 0, 0, 0) } return success; } return success; } function _beforeUnstake( address ownerAddress, address receiverAddress, uint256 amount function _afterUnstake( address ownerAddress, address receiverAddress, uint256 amount function _unsafeTransfer( address receiverAddress, uint256 amount, bool limit ) internal virtual returns (bool) { address payable wallet = payable(receiverAddress); bool success; if (limit) { assembly { success := call(10000, wallet, amount, 0, 0, 0, 0) } return success; } return success; } function _beforeUnstake( address ownerAddress, address receiverAddress, uint256 amount function _afterUnstake( address ownerAddress, address receiverAddress, uint256 amount function _unsafeTransfer( address receiverAddress, uint256 amount, bool limit ) internal virtual returns (bool) { address payable wallet = payable(receiverAddress); bool success; if (limit) { assembly { success := call(10000, wallet, amount, 0, 0, 0, 0) } return success; } return success; } (success, ) = wallet.call{value: amount}(""); function getFreeBalance() public view virtual returns (uint256) { return address(this).balance; } function getTokens() external view virtual returns (address, address) { return (address(_bearingToken), address(_certificateToken)); } }
5,038,647
/** *Submitted for verification at Etherscan.io on 2022-02-24 */ // Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts/utils/cryptography/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.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; } } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.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); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @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; } } // File contracts/xmferpets.sol contract xmferspets is ERC721, Ownable { using Counters for Counters.Counter; string public baseURI; string public contractURI; string public constant baseExtension = ".json"; address public constant proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; bytes32 public merkleRoot = 0x7cccd35f224c6fbb86274f2e458d93423f1c4a773545381094d930d8bc34a199; Counters.Counter private _totalSupply; uint256 private _publicSupply; uint256 public MAX_SUPPLY_PUBLIC = 4200; uint256 public price = 0.024 ether; uint256 public holders_price = 0.0042 ether; uint256 public saleID; uint256 public constant MAX_PER_WALLET_PUBLIC = 2; bool public claimSale = false; bool public publicSale = false; bool public reveal = false; mapping(uint256 => bool) public petTypeAvailableToMint; mapping(uint256 => uint256) public petAsignToTokenID; mapping(uint256 => mapping(address => uint256)) public claimWalletsMinted; mapping(uint256 => mapping(address => uint256)) public hodlersMinted; mapping(uint256 => mapping(address => uint256)) public walletsMinted; IERC721 xmfers = IERC721(0xB156ADf8523FdC6152aFFdbA076a2143FD7e3c69); constructor() ERC721("xmferpets", "xmp") { petTypeAvailableToMint[0] = true; petTypeAvailableToMint[1] = true; } function claim(uint256 _amountToMint, uint256 _typeOfPet, uint256 _maxAmount, bytes32[] calldata _merkleProof) external payable { address _caller = _msgSender(); require(claimSale, "Claim not active"); require(xmfers.balanceOf(_caller) > 0, "Non believer"); require(petTypeAvailableToMint[_typeOfPet], "Not allowed to mint this type of pet"); require(claimWalletsMinted[saleID][_caller] + _amountToMint <= _maxAmount, "Not allow to mint more"); require(_amountToMint > 0, "Not 0 mints"); require(tx.origin == _caller, "No contracts"); bytes32 leaf = keccak256(abi.encodePacked(_caller, _maxAmount)); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof"); claimWalletsMinted[saleID][_caller] += _amountToMint; for (uint256 i; i < _amountToMint; i++) { if(_typeOfPet > 0){ petAsignToTokenID[_totalSupply.current()] = _typeOfPet; } _safeMint(_caller, _totalSupply.current()); _totalSupply.increment(); } } function holders(uint256 _amountToMint, uint256 _typeOfPet) external payable { address _caller = _msgSender(); require(MAX_SUPPLY_PUBLIC >= _publicSupply + _amountToMint, "Exceeds max supply"); require(publicSale, "Public sale not active"); require(xmfers.balanceOf(_caller) > 0, "Non believer"); require(petTypeAvailableToMint[_typeOfPet], "Not allowed to mint this type of pet"); require(hodlersMinted[saleID][_caller] + _amountToMint <= MAX_PER_WALLET_PUBLIC, "Not allow to mint more"); require(_amountToMint > 0, "Not 0 mints"); require(tx.origin == _caller, "No contracts"); require(_amountToMint * holders_price == msg.value, "Invalid funds provided"); hodlersMinted[saleID][_caller] += _amountToMint; unchecked { _publicSupply += _amountToMint; } for (uint256 i; i < _amountToMint; i++) { if(_typeOfPet > 0){ petAsignToTokenID[_totalSupply.current()] = _typeOfPet; } _safeMint(_caller, _totalSupply.current()); _totalSupply.increment(); } } function mint(uint256 _amountToMint, uint256 _typeOfPet) external payable { address _caller = _msgSender(); require(MAX_SUPPLY_PUBLIC >= _publicSupply + _amountToMint, "Exceeds max supply"); require(publicSale, "Public sale not active"); require(petTypeAvailableToMint[_typeOfPet], "Not allowed to mint this type of pet"); require(walletsMinted[saleID][_caller] + _amountToMint <= MAX_PER_WALLET_PUBLIC, "Not allow to mint more"); require(_amountToMint > 0, "Not 0 mints"); require(tx.origin == _caller, "No contracts"); require(_amountToMint * price == msg.value, "Invalid funds provided"); walletsMinted[saleID][_caller] += _amountToMint; unchecked { _publicSupply += _amountToMint; } for (uint256 i; i < _amountToMint; i++) { if(_typeOfPet > 0){ petAsignToTokenID[_totalSupply.current()] = _typeOfPet; } _safeMint(_caller, _totalSupply.current()); _totalSupply.increment(); } } function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; (bool success, ) = _msgSender().call{value: balance}(""); require(success, "Failed to send"); } function changeSupply(uint256 _MAX_SUPPLY) external onlyOwner { require(_MAX_SUPPLY >= _totalSupply.current(), "Cant put less supply"); MAX_SUPPLY_PUBLIC = _MAX_SUPPLY; } function mintingOnes(uint256 _amountToMint) external onlyOwner { for (uint256 i; i < _amountToMint; i++) { _safeMint(_msgSender(), _totalSupply.current()); _totalSupply.increment(); } } function resetPublicSupplyCounter() external onlyOwner { _publicSupply = 0; } function setBaseURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; } function setContractURI(string memory _contractURI) external onlyOwner { contractURI = _contractURI; } function setRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } function setSaleID(uint256 _saleID) external onlyOwner { saleID = _saleID; } function setPrices(uint256 _price, uint256 _holders_price) external onlyOwner { price = _price; holders_price = _holders_price; } function setSaleState(bool _claimSale, bool _publicSale) external onlyOwner { claimSale = _claimSale; publicSale = _publicSale; } function setRevealState(bool _reveal) external onlyOwner { reveal = _reveal; } function setPetAvailabilityState(uint256 _typeOfPet, bool _available) external onlyOwner { petTypeAvailableToMint[_typeOfPet] = _available; } function totalSupply() external view returns (uint256) { return _totalSupply.current(); } function publicSupply() external view returns (uint256) { return _publicSupply; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Token does not exist."); return bytes(baseURI).length > 0 ? string( abi.encodePacked( baseURI, reveal ? Strings.toString(_tokenId) : string(abi.encodePacked(Strings.toString(petAsignToTokenID[_tokenId]), "_holder")), baseExtension ) ) : ""; } } contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
Initializes the contract setting the deployer as the initial owner./
function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } constructor() { _transferOwnership(_msgSender()); }
10,544,852
./full_match/1/0xA1F18e3E99976AdA8F598458c6c0dc0b5c713Db4/sources/contracts/ERC721ACMUpgradeable.sol
Returns whether `tokenId` exists. Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`),/
function _exists(uint256 tokenId) internal view returns (bool) { return (tokenId >= baseTokenId) && (tokenId < _currentIndex); }
3,075,823
./full_match/8453/0x7D691e6b03b46B5A5769299fC9a32EaC690B7abc/sources/contracts/utils/ERC2612Permitter.sol
Sets the amount of an `ERC20` token that this contract is allowed to transfer from `msg.sender` using an old version of `EIP2612`. token The address of the token to permit. nonce Deduplicates permit transactions. expiry The timestamp that the transaction must go through before. allowed True to allow all, false to allow zero. v secp256k1 signature r secp256k1 signature s secp256k1 signature/
function erc2612Permit(address token, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external override { IERC20PermitC(token).permit(msg.sender, address(this), nonce, expiry, allowed, v, r, s); }
11,557,837
./full_match/11155111/0x9A35CB46B76261967CC4fF8cCfa8F634a83c2445/sources/src/common/token/ERC1155/ERC1155.sol
See {IERC1155-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public virtual override whenNotDestroyed whenNotPaused { require(_msgSender() != operator, 'ERC1155: setting approval status for self'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
3,827,908
pragma solidity 0.5.17; import "./TreasuryBase.sol"; import "./TreasuryFactoryBase.sol"; /** * @author Quant Network * @title Allows contracts holding mapp, treasury and gateway rules to be easily found */ contract RuleLists is UpgradeableProxy { // the rules that the mapps needs to abide by bytes constant private mappRules1 = '1.mappRules'; // the rules that the treasury needs to abide by bytes constant private treasuryRules1 = '1.treasuryRules'; // the rules that the gateways needs to abide by bytes constant private gatewayRules1 = '1.gatewayRules'; // the number of rules that the mapps needs to abide by bytes constant private mappRuleIndex1 = '1.mappRuleIndex'; // the number of rules that the treasury needs to abide by bytes constant private treasuryRuleIndex1 = '1.treasuryRuleIndex'; // the number of rules that the gateways needs to abide by bytes constant private gatewayRuleIndex1 = '1.gatewayRuleIndex'; // the linked treasury contract bytes constant private treasuryAddress1 = '1.treasuryaddress'; // this contract's current registered speed bumps. Array index [0] is for mapps, [1] for treasury and [2] for gateway. bytes constant private speedBumpRule1 = '1.speedBump.rule'; bytes constant private speedBumpTimeCreated1 = '1.speedBump.timeCreated'; bytes constant private speedBumpWaitingHours1 = '1.speedBump.waitingHours'; // The event fired when a new rule is stored here: event addedRule(string stakeholder, uint256 index); // The event fired when a rule has been used: event usedRule(uint16 ruleIndex, address slashed, uint256 value); // The event fired when a speed bump has been updated event updatedSpeedBump(address rule, uint8 speedBumpIndex); /** * All functions with this modifier can only be called by the current treasury address * of the contract */ modifier onlyTreasury(){ TreasuryBase t = TreasuryBase(treasuryAddress()); if (msg.sender != t.operatorAddress()){ revert("Only the treasury contract's operator address can modify this contract's associated storage"); } else { _; // otherwise carry on with the computation } } /** * Sets the contract and initialises the variables * @param linkedTreasuryContract - the address of the linked treasury contract */ function initialize (address linkedTreasuryContract) external { require(!initialized(),"contract can only be initialised once"); addressStorage[keccak256(treasuryAddress1)] = linkedTreasuryContract; initializeNow(); //sets this contract to initialized } /** * Adds a rule to the correct stakeholder's list. All rules should follow the template code * @param speedBumpIndex - which speed bump to use: 0 for mapp, 1 for treasury, 2 for gateway * param: speedBumps[speedBumpIndex].rule - the address of a smart contract detailing this specific rule */ function addRule(uint8 speedBumpIndex) external onlyTreasury() { require(((speedBumpIndex >= 0)&&(speedBumpIndex <= 2)), "Speed bump index must between 0 and 2 inclusive"); require(speedBumpTimeCreated(speedBumpIndex) > 0, "Time created must be >0 (to stop replays of the speed bump)"); require(now > speedBumpTimeCreated(speedBumpIndex) + (speedBumpWaitingHours(speedBumpIndex)*1 hours), "The speed bump time period must have passed"); if (speedBumpIndex == 0){ //add rule mappRules(speedBumpRule(0)); //wipe speed bump deleteSpeedBump(0); //update rule emit addedRule("mapps", mappRuleIndex()); } else if (speedBumpIndex == 1){ //add rule treasuryRules(speedBumpRule(1)); //wipe speed bump deleteSpeedBump(1); //update rule emit addedRule("treasury", treasuryRuleIndex()); } else if (speedBumpIndex == 2){ //add rule gatewayRules(speedBumpRule(2)); //wipe speed bump deleteSpeedBump(2); //update rule emit addedRule("gateways", gatewayRuleIndex()); } } /** * Creates a SpeedBump request for either a mapp, treasury or gateway update as defined by the stakeholder parameter * @param stakeholder - what will this speedBump be used for. * Pass through "mapp" to subsequently use the addRule() function to add a rule for the mapps * Pass through "treasury" to subsequently use the addRule() function to add a rule for the treasury * Pass through "gateway" to subsequently use the addRule() function to add a rule for the gateways * @param rule - the address of a smart contract detailing this specific rule */ function updateSpeedBump(string calldata stakeholder, address rule) external onlyTreasury() { if (keccak256(abi.encodePacked(stakeholder)) == keccak256(abi.encodePacked("mapp"))){ addSpeedBump(rule, 0); //emit event emit updatedSpeedBump(rule,0); } else if (keccak256(abi.encodePacked(stakeholder)) == keccak256(abi.encodePacked("treasury"))){ addSpeedBump(rule, 1); //emit event emit updatedSpeedBump(rule,1); } else if (keccak256(abi.encodePacked(stakeholder)) == keccak256(abi.encodePacked("gateway"))){ addSpeedBump(rule, 2); //emit event emit updatedSpeedBump(rule,2); } else { revert("The rule needs to be for a mapp, treasury or gateway"); } } /** * Uses a rule. Only rule contracts themselves can invoke this function * @param toSlash - which address has broken the rule * @param multiple - what is the multiple for the slash used to calculate the final penalty. * This will be the function fee for gateways and the number of gateways for mapps * @param ruleIndex - the index of the stakeholder rule broken (0 = mapp, 1 = treasury, 2 = gateway) */ function useRule(address toSlash, uint multiple, uint16 ruleIndex) external { uint256 multipler; require(((ruleIndex >= 0)&&(ruleIndex <= 2)), "Rule index must between 0 and 2 inclusive"); //load the correct deposit contract TreasuryBase t = TreasuryBase(treasuryAddress()); FactoryBase f = FactoryBase(t.treasurysFactory()); address escrowedDepositAddr; if (ruleIndex == 0){ require (mappRules(ruleIndex) == msg.sender, "Calling address must be a mapp rule"); multipler = t.mappDisputeFeeMultipler(); escrowedDepositAddr = f.mappDeposit(toSlash); } else if (ruleIndex == 1){ require (treasuryRules(ruleIndex) == msg.sender, "Calling address must be a treasury rule"); multipler = t.treasuryPenaltyMultipler(); escrowedDepositAddr = t.treasurysDeposit(); } else if (ruleIndex == 2){ require (gatewayRules(ruleIndex) == msg.sender, "Calling address must be a gateway rule"); multipler = t.gatewayPenaltyMultipler(); escrowedDepositAddr = f.gatewayDeposit(toSlash); } //take the correct slashed amount from the deposit contract uint256 penalty = multipler*multiple; require(penalty > 0, "penalty <= 0"); EscrowedDepositAbstract(escrowedDepositAddr).deductDeposit(penalty, msg.sender); //emit event emit usedRule(ruleIndex, toSlash, penalty); } /** * Adds a new mapp rule * @param newRule - the address describing the new rule */ function mappRules(address newRule) internal { //get current index uint16 index = mappRuleIndex(); index += 1; addressStorage[keccak256(abi.encodePacked(mappRules1,index))] = newRule; //increase index uint16Storage[keccak256(mappRuleIndex1)] = index; } /** * Adds a new treasury rule * @param newRule - the address describing the new rule */ function treasuryRules(address newRule) internal { //get current index uint16 index = treasuryRuleIndex(); index += 1; addressStorage[keccak256(abi.encodePacked(treasuryRules1,index))] = newRule; //increase index uint16Storage[keccak256(treasuryRuleIndex1)] = index; } /** * Adds a new gateway rule * @param newRule - the address describing the new rule */ function gatewayRules(address newRule) internal { //get current index uint16 index = gatewayRuleIndex(); index += 1; addressStorage[keccak256(abi.encodePacked(gatewayRules1,index))] = newRule; //increase index uint16Storage[keccak256(treasuryRuleIndex1)] = index; } /** * Adds a new speed bump * @param newRule - the address describing the new rule * @param speedBumpIndex - which speed bump is being added */ function addSpeedBump(address newRule, uint8 speedBumpIndex) internal { TreasuryBase t = TreasuryBase(treasuryAddress()); addressStorage[keccak256(abi.encodePacked(speedBumpRule1,speedBumpIndex))] = newRule; uint256Storage[keccak256(abi.encodePacked(speedBumpTimeCreated1,speedBumpIndex))] = now; uint16Storage[keccak256(abi.encodePacked(speedBumpWaitingHours1,speedBumpIndex))] = t.speedBumpHours(); } /** * Deletes a speed bump * @param speedBumpIndex - which speed bump is being deleted */ function deleteSpeedBump(uint8 speedBumpIndex) internal { addressStorage[keccak256(abi.encodePacked(speedBumpRule1,speedBumpIndex))] = address(0x0); uint256Storage[keccak256(abi.encodePacked(speedBumpTimeCreated1,speedBumpIndex))] = 0; uint16Storage[keccak256(abi.encodePacked(speedBumpWaitingHours1,speedBumpIndex))] = 0; } /** * @return - the admin of the proxy. Only the admin address can upgrade the smart contract logic */ function admin() public view returns (address) { TreasuryBase t = TreasuryBase(treasuryAddress()); return t.admin(); } /** * @return - the number of hours wait time for any critical update */ function speedBumpHours() public view returns (uint16){ TreasuryBase t = TreasuryBase(treasuryAddress()); return t.speedBumpHours(); } /** * Reads the linked treasury contract address * @return - the treasury contract */ function treasuryAddress() public view returns (address) { return addressStorage[keccak256(treasuryAddress1)]; } /** * Reads the contract rule address in a SpeedBump * @param speedBumpIndex - the speed bump to look up * @return - the specific rule */ function speedBumpRule(uint8 speedBumpIndex) public view returns (address) { return addressStorage[keccak256(abi.encodePacked(speedBumpRule1,speedBumpIndex))]; } /** * Reads the time the speedBump was created at * @param speedBumpIndex - the speed bump to look up * @return - the creation time */ function speedBumpTimeCreated(uint8 speedBumpIndex) public view returns (uint256) { return uint256Storage[keccak256(abi.encodePacked(speedBumpTimeCreated1,speedBumpIndex))]; } /** * Reads the number of hours until the SpeedBump can be used * @param speedBumpIndex - the speed bump to look up * @return - the number of hours */ function speedBumpWaitingHours(uint8 speedBumpIndex) public view returns (uint16) { return uint16Storage[keccak256(abi.encodePacked(speedBumpWaitingHours1,speedBumpIndex))]; } /** * Reads a specific mapp rule smart contract address * @param index - the specific index of the rule to read * @return - the address */ function mappRules(uint16 index) public view returns (address){ return addressStorage[keccak256(abi.encodePacked(mappRules1,index))]; } /** * Reads a specific treasury rule smart contract address * @param index - the specific index of the rule to read * @return - the address */ function treasuryRules(uint16 index) public view returns (address){ return addressStorage[keccak256(abi.encodePacked(treasuryRules1,index))]; } /** * Reads a specific gateway rule smart contract address * @param index - the specific index of the rule to read * @return - the address */ function gatewayRules(uint16 index) public view returns (address){ return addressStorage[keccak256(abi.encodePacked(gatewayRules1,index))]; } /** * Reads number of mapp rule smart contracts * @return - the number of mapp rules */ function mappRuleIndex() public view returns (uint16){ return uint16Storage[keccak256(mappRuleIndex1)]; } /** * Reads number of treasury rule smart contracts * @return - the number of treasury rules */ function treasuryRuleIndex() public view returns (uint16){ return uint16Storage[keccak256(treasuryRuleIndex1)]; } /** * Reads number of gateway rule smart contracts * @return - the number of gateway rules */ function gatewayRuleIndex() public view returns (uint16){ return uint16Storage[keccak256(gatewayRuleIndex1)]; } }
Creates a SpeedBump request for either a mapp, treasury or gateway update as defined by the stakeholder parameter stakeholder - what will this speedBump be used for. Pass through "mapp" to subsequently use the addRule() function to add a rule for the mapps Pass through "treasury" to subsequently use the addRule() function to add a rule for the treasury Pass through "gateway" to subsequently use the addRule() function to add a rule for the gateways rule - the address of a smart contract detailing this specific rule/emit eventemit eventemit event
function updateSpeedBump(string calldata stakeholder, address rule) external onlyTreasury() { if (keccak256(abi.encodePacked(stakeholder)) == keccak256(abi.encodePacked("mapp"))){ addSpeedBump(rule, 0); emit updatedSpeedBump(rule,0); addSpeedBump(rule, 1); emit updatedSpeedBump(rule,1); addSpeedBump(rule, 2); emit updatedSpeedBump(rule,2); revert("The rule needs to be for a mapp, treasury or gateway"); } }
12,885,922
pragma solidity >=0.5.0 <0.6.0; contract eetp { address payable agent; // energy agent owns smart contract address payable network; // distribution network uint penality; // penality for cancelling struct offer { address payable buyer; uint starting; uint duration; bool confirmed; } // hash of energy offer (processed by energy agent) mapped to offer mapping (bytes32 => offer) public offers; event bought(bytes32 trans, address payable buyer); event confirmed(bytes32 trans, address payable buyer); constructor(address payable _network) public payable { agent = msg.sender network = _network penality = 100; } modifier valid(uint _starting) { require(_starting > now); _; } function buy(bytes32 _trans, uint _starting, uint _duration) public valid(_starting) payable { offer memory anOffer; // offer must be available (ie hasn't been bought yet) if (offers[_trans].buyer == address(0x0)) { anOffer.buyer = msg.sender; anOffer.starting = _starting; anOffer.duration = _duration; offers[_trans] = anOffer; emit bought(_trans, msg.sender); } } function cancel(bytes32 _trans) public payable { if (offers[_trans].buyer == msg.sender) { // buyer can cancel is starting time for energy transfer hasn't yet started // must pay penality if (offers[_trans].starting > now) { offers[_trans].buyer = address(0x0); // person must pay penality } } } modifier identity() { require(msg.sender == network); _; } // network confrims energy transfer is possible, if not offer is invalid function confirm(bytes32 _trans) public identity payable { if (offers[_trans].starting > now) { offers[_trans].confirmed = true; emit confirmed(_trans, offers[_trans].buyer); } } // buyer pays once offer has been confirmed function pay(bytes32 _trans) public payable { if (offers[_trans].buyer == msg.sender && offers[_trans].confirmed == true) { // payment } } }
offer must be available (ie hasn't been bought yet)
function buy(bytes32 _trans, uint _starting, uint _duration) public valid(_starting) payable { offer memory anOffer; if (offers[_trans].buyer == address(0x0)) { anOffer.buyer = msg.sender; anOffer.starting = _starting; anOffer.duration = _duration; offers[_trans] = anOffer; emit bought(_trans, msg.sender); } }
13,019,208
pragma solidity ^0.4.21; contract TwoXJackpot { using SafeMath for uint256; address public contractOwner; // Address of the contract creator // BuyIn Object, holding information of each Buy In // Also used to store information about winners in each game struct BuyIn { uint256 value; address owner; } // Game Object, holding information of each Game played struct Game { BuyIn[] buyIns; // FIFO queue address[] winners; // Jackpot Winners addresses uint256[] winnerPayouts; // Jackpot Winner Payouts uint256 gameTotalInvested; // Total Invested in game uint256 gameTotalPaidOut; // Total Paid Out in game uint256 gameTotalBacklog; // Total Amount waiting to payout uint256 index; // The current BuyIn queue index mapping (address => uint256) totalInvested; // Total invested for a given address mapping (address => uint256) totalValue; // Total value for a given address mapping (address => uint256) totalPaidOut; // Total paid out for a given address } mapping (uint256 => Game) public games; // Map game index to the game uint256 public gameIndex; // The current Game Index // Timestamp of the last action. // Jackpot uint256 public jackpotBalance; // Total balance of Jackpot (before re-seed deduction) address public jackpotLastQualified; // Last Purchaser, in running for Jackpot claim address public jackpotLastWinner; // Last Winner Address uint256 public jackpotLastPayout; // Last Payout Amount (after re-seed deduction) uint256 public jackpotCount; // Number of jackpots for sliding payout. // Timestamp of Game Start uint256 public gameStartTime; // Game Start Time uint256 public roundStartTime; // Round Start Time, used to pause the game uint256 public lastAction; // Last Action Timestamp uint256 public timeBetweenGames = 24 hours; // Time between games (4 Jackpots hit = 1 game) uint256 public timeBeforeJackpot = 30 minutes; // Time between last purchase and jackpot payout (increases) uint256 public timeBeforeJackpotReset = timeBeforeJackpot; // To reset the jackpot timer uint256 public timeIncreasePerTx = 1 minutes; // How much time to increment the jackpot for each buy uint256 public timeBetweenRounds = 5 minutes; // Time between rounds (each Round has 5 minute timeout) // Buy In configuration logic uint256 public buyFee = 90; // This ends up being a 10% fee towards Jackpot uint256 public minBuy = 50; // Jackpot / 50 = 2% Min buy uint256 public maxBuy = 2; // Jackpot / 2 = 50% Max buy uint256 public minMinBuyETH = 0.02 ether; // Min buy in should be more then 0.02 ETH uint256 public minMaxBuyETH = 0.5 ether; // Max buy in should be more then 0.5 ETH uint256[] public gameReseeds = [90, 80, 60, 20]; // How much money reseeds to the next round modifier onlyContractOwner() { require(msg.sender == contractOwner); _; } modifier isStarted() { require(now >= gameStartTime); // Check game started require(now >= roundStartTime); // Check round started _; } /** * Events */ event Purchase(uint256 amount, address depositer); event Seed(uint256 amount, address seeder); function TwoXJackpot() public { contractOwner = msg.sender; gameStartTime = now + timeBetweenGames; lastAction = gameStartTime; } // // // ADMIN FUNCTIONS // // // // Change the start time for fair launch function changeStartTime(uint256 _time) public onlyContractOwner { require(now < _time); // only allow changing it to something in the future gameStartTime = _time; lastAction = gameStartTime; // Don't forget to update last action too :) } // Change the start time for fair launch function updateTimeBetweenGames(uint256 _time) public onlyContractOwner { timeBetweenGames = _time; // Time after Jackpot claim we allow new buys. } // // // User Functions // // // // Anyone can seed the jackpot, since its non-refundable. It will pay 10% forward to next game. // Beware, there is no way to get your seed back unless you win the jackpot. function seed() public payable { jackpotBalance += msg.value; // Increase the value of the jackpot by this much. //emit Seed event emit Seed(msg.value, msg.sender); } function purchase() public payable isStarted { // Check if the game is still running if (now > lastAction + timeBeforeJackpot && jackpotLastQualified != 0x0) { claim(); // Next game/round will start, return back money to user if (msg.value > 0) { msg.sender.transfer(msg.value); } return; } // Check if JackPot is less then 1 ETH, then // use predefined minimum and maximum buy in values if (jackpotBalance <= 1 ether) { require(msg.value >= minMinBuyETH); // >= 0.02 ETH require(msg.value <= minMaxBuyETH); // <= 0.5 ETH } else { uint256 purchaseMin = SafeMath.mul(msg.value, minBuy); uint256 purchaseMax = SafeMath.mul(msg.value, maxBuy); require(purchaseMin >= jackpotBalance); require(purchaseMax <= jackpotBalance); } uint256 valueAfterTax = SafeMath.div(SafeMath.mul(msg.value, buyFee), 100); // Take a 10% fee for Jackpot, example on 1ETH Buy: 0.9 = (1.0 * 90) / 100 uint256 potFee = SafeMath.sub(msg.value, valueAfterTax); // Calculate the absolute number to put into pot. jackpotBalance += potFee; // Add it to the jackpot jackpotLastQualified = msg.sender; // You are now the rightly heir to the Jackpot...for now... lastAction = now; // Reset jackpot timer timeBeforeJackpot += timeIncreasePerTx; // Increase Jackpot Timer by 1 minute. uint256 valueMultiplied = SafeMath.mul(msg.value, 2); // Double it // Update Global Investing Information games[gameIndex].gameTotalInvested += msg.value; games[gameIndex].gameTotalBacklog += valueMultiplied; // Update Game Investing Information games[gameIndex].totalInvested[msg.sender] += msg.value; games[gameIndex].totalValue[msg.sender] += valueMultiplied; // Push new Buy In information in our game list of buy ins games[gameIndex].buyIns.push(BuyIn({ value: valueMultiplied, owner: msg.sender })); //Emit a deposit event. emit Purchase(msg.value, msg.sender); while (games[gameIndex].index < games[gameIndex].buyIns.length && valueAfterTax > 0) { BuyIn storage buyIn = games[gameIndex].buyIns[games[gameIndex].index]; if (valueAfterTax < buyIn.value) { buyIn.owner.transfer(valueAfterTax); // Update game information games[gameIndex].gameTotalBacklog -= valueAfterTax; games[gameIndex].gameTotalPaidOut += valueAfterTax; // game paid out and value update games[gameIndex].totalPaidOut[buyIn.owner] += valueAfterTax; games[gameIndex].totalValue[buyIn.owner] -= valueAfterTax; buyIn.value -= valueAfterTax; valueAfterTax = 0; } else { buyIn.owner.transfer(buyIn.value); // Update game information games[gameIndex].gameTotalBacklog -= buyIn.value; games[gameIndex].gameTotalPaidOut += buyIn.value; // game paid out and value update games[gameIndex].totalPaidOut[buyIn.owner] += buyIn.value; games[gameIndex].totalValue[buyIn.owner] -= buyIn.value; valueAfterTax -= buyIn.value; buyIn.value = 0; games[gameIndex].index++; } } } // Claim the Jackpot function claim() public payable isStarted { require(now > lastAction + timeBeforeJackpot); require(jackpotLastQualified != 0x0); // make sure last jackpotLastQualified is not 0x0 // Each game has 4 Jackpot payouts, increasing in payout percentage. // Funds owed to you do not reset between Jackpots, but will reset after 1 game (4 Jackpots) uint256 reseed = SafeMath.div(SafeMath.mul(jackpotBalance, gameReseeds[jackpotCount]), 100); uint256 payout = jackpotBalance - reseed; jackpotLastQualified.transfer(payout); // payout entire jackpot minus seed. jackpotBalance = reseed; jackpotLastWinner = jackpotLastQualified; jackpotLastPayout = payout; // Let's store now new winner in list of game winners games[gameIndex].winners.push(jackpotLastQualified); games[gameIndex].winnerPayouts.push(payout); // RESET all the settings timeBeforeJackpot = timeBeforeJackpotReset; // reset to 30 min on each round timer jackpotLastQualified = 0x0; // set last qualified to 0x0 if(jackpotCount == gameReseeds.length - 1){ // Reset all outstanding owed money after 4 claimed jackpots to officially restart the game. gameStartTime = now + timeBetweenGames; // Restart the game in a specified period (24h) lastAction = gameStartTime; // Reset last action to the start of the game gameIndex += 1; // Next Game! jackpotCount = 0; // Reset Jackpots back to 0 after game end. } else { lastAction = now + timeBetweenRounds; roundStartTime = lastAction; jackpotCount += 1; } } // Fallback, sending any ether will call purchase() function () public payable { purchase(); } // PUBLIC METHODS TO RETRIEVE DATA IN UI // Return Current Jackpot Info // [ JackPotBalance, jackpotLastQualified, jackpotLastWinner, jackpotLastPayout, // jackpotCount, gameIndex, gameStartTime, timeTillRoundEnd, roundStartTime] function getJackpotInfo() public view returns (uint256, address, address, uint256, uint256, uint256, uint256, uint256, uint256) { return ( jackpotBalance, jackpotLastQualified, jackpotLastWinner, jackpotLastPayout, jackpotCount, gameIndex, gameStartTime, lastAction + timeBeforeJackpot, roundStartTime ); } // Return player game info based on game index and player address // [ totalInvested, totalValue, totalPaidOut] function getPlayerGameInfo(uint256 _gameIndex, address _player) public view returns (uint256, uint256, uint256) { return ( games[_gameIndex].totalInvested[_player], games[_gameIndex].totalValue[_player], games[_gameIndex].totalPaidOut[_player] ); } // Get user game info connected to current game function getMyGameInfo() public view returns (uint256, uint256, uint256) { return getPlayerGameInfo(gameIndex, msg.sender); } // Return all the game constants, setting the game function getGameConstants() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256[]) { return ( timeBetweenGames, timeBeforeJackpot, minMinBuyETH, minMaxBuyETH, minBuy, maxBuy, gameReseeds ); } // Return game information based on game index function getGameInfo(uint256 _gameIndex) public view returns (uint256, uint256, uint256, address[], uint256[]) { return ( games[_gameIndex].gameTotalInvested, games[_gameIndex].gameTotalPaidOut, games[_gameIndex].gameTotalBacklog, games[_gameIndex].winners, games[_gameIndex].winnerPayouts ); } // Return current running game info function getCurrentGameInfo() public view returns (uint256, uint256, uint256, address[], uint256[]) { return getGameInfo(gameIndex); } // Return time when next game will start function getGameStartTime() public view returns (uint256) { return gameStartTime; } // Return end time for the jackpot round function getJackpotRoundEndTime() public view returns (uint256) { return lastAction + timeBeforeJackpot; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Return current running game info
function getCurrentGameInfo() public view returns (uint256, uint256, uint256, address[], uint256[]) { return getGameInfo(gameIndex); }
5,504,576
./partial_match/1/0x162C85198DFCBbd195970007156FB17bCbAb9F9E/sources/NFT1155MarketV2.sol
uint256 ethAmount = 0; SupportBuyCurrency memory supportBuyCurrency = _supportBuyCurrency[currency_]; if (supportBuyCurrency.isDeflation) { ethAmount = exactTokenToEth(currency_, price); } else { ethAmount = tokenToExactEth(currency_, price); }
function buy(uint index,uint256 _amount, address currency_) public nonReentrant mustNotSellingOut(index) checkSupportBuyCurrendy(currency_) payable { uint256 amount = _amount; SalesObject storage obj = _salesObjects[index]; require (obj.amount >= amount, "umm..... It's too much"); uint256 unitPrice = this.getSalesPrice(index); uint256 price = unitPrice.mul(amount); uint256 tipsFee = price.mul(_tipsFeeRate).div(_baseRate); uint256 purchase = price.sub(tipsFee); if (obj.currency == currency_){ if (obj.currency == address(0x0)) { require (msg.value >= this.getSalesPrice(index), "umm..... your price is too low"); uint256 returnBack = msg.value.sub(price); if(returnBack > 0) { msg.sender.transfer(returnBack); } if(tipsFee > 0) { _tipsFeeWallet.transfer(tipsFee); } obj.seller.transfer(purchase); IERC20(obj.currency).safeTransferFrom(msg.sender, _tipsFeeWallet, tipsFee); IERC20(obj.currency).safeTransferFrom(msg.sender, obj.seller, purchase); } if (obj.currency == address(0x0)){ uint256 ethAmount = tokenToEth(currency_, price); require (ethAmount >= price, "umm..... your price is too low"); uint256 returnBack = ethAmount.sub(price).add(msg.value); if(returnBack > 0) { msg.sender.transfer(returnBack); } if(tipsFee > 0) { _tipsFeeWallet.transfer(tipsFee); } obj.seller.transfer(purchase); } } obj.nft.safeTransferFrom(address(this), msg.sender, obj.tokenId, amount, ""); obj.buyers.push(msg.sender); obj.amount = obj.amount.sub(amount); if (obj.amount == 0) { obj.status = 1; } if(_isRewardBuyerDandy) { _dandy.mint(msg.sender, _buyerRewardDandy); } index, obj.tokenId, msg.sender, price, tipsFee, amount, obj.amount ); }
2,696,111
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol
Internal view function to get the current price of BOOGIE on Uniswap
function _getBoogiePrice() internal view returns (uint256 boogiePrice) { uint256 boogieBalance = boogie.balanceOf(boogiePoolAddress); if (boogieBalance > 0) { boogiePrice = 10**18 * weth.balanceOf(boogiePoolAddress) / boogieBalance; } }
4,927,165
./partial_match/1/0x1955D86f5b369Be4581Fb2D346B403d362883aC7/sources/EmployeeIDBadges.sol
Appends `data` to `buffer`. Returns the same buffer, so that it can be used for function chaining. @solidity memory-safe-assembly Some random prime number to multiply `capacity`, so that we know that the `capacity` is for a dynamic buffer. Selected to be larger than any memory pointer realistically. Extract `capacity`, and set it to 0, if it is not a multiple of `prime`. Expand / Reallocate memory if required. Note that we need to allocate an exta word for the length, and and another extra word as a safety word (giving a total of 0x40 bytes). Without the safety word, the data at the next free memory word can be overwritten, because the backwards copying can exceed the buffer space used for storage. Approximately double the memory with a heuristic, ensuring more than enough space for the combined data, rounding up to the next multiple of 32. If next word after current buffer is not eligible for use. Set the `newBufferData` to point to the word after capacity. Reallocate the memory. Store the `newBufferData`. Copy `bufferData` one word at a time, backwards.
function append(DynamicBuffer memory buffer, bytes memory data) internal pure returns (DynamicBuffer memory) { assembly { if mload(data) { let w := not(31) let bufferData := mload(buffer) let bufferDataLength := mload(bufferData) let newBufferDataLength := add(mload(data), bufferDataLength) let prime := 1621250193422201 let capacity := mload(add(bufferData, w)) capacity := mul(div(capacity, prime), iszero(mod(capacity, prime))) let newCapacity := and(add(capacity, add(or(capacity, newBufferDataLength), 32)), w) if iszero(eq(mload(0x40), add(bufferData, add(0x40, capacity)))) { let newBufferData := add(mload(0x40), 0x20) mstore(0x40, add(newBufferData, add(0x40, newCapacity))) mstore(buffer, newBufferData) mstore(add(newBufferData, o), mload(add(bufferData, o))) } break } break } mstore(add(output, o), mload(add(data, o))) }
3,590,635
pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Modifiable * @notice A contract with basic modifiers */ contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SelfDestructible * @notice Contract that allows for self-destruction */ contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Ownable * @notice A modifiable that has ownership roles */ contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Servable * @notice An ownable that contains registered services and their actions */ contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string action) { require(isEnabledServiceAction(msg.sender, action)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathIntLib * @dev Math operations with safety checks that throw on error */ library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbUintsLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; uint256 value; } struct BlockNumbUints { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbUints storage self) internal view returns (uint256) { return valueAt(self, block.number); } function currentEntry(BlockNumbUints storage self) internal view returns (Entry) { return entryAt(self, block.number); } function valueAt(BlockNumbUints storage self, uint256 _blockNumber) internal view returns (uint256) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbUints storage self, uint256 _blockNumber) internal view returns (Entry) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbUints storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbUints storage self) internal view returns (Entry[]) { return self.entries; } function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbIntsLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; int256 value; } struct BlockNumbInts { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbInts storage self) internal view returns (int256) { return valueAt(self, block.number); } function currentEntry(BlockNumbInts storage self) internal view returns (Entry) { return entryAt(self, block.number); } function valueAt(BlockNumbInts storage self, uint256 _blockNumber) internal view returns (int256) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbInts storage self, uint256 _blockNumber) internal view returns (Entry) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbInts storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbInts storage self) internal view returns (Entry[]) { return self.entries; } function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbDisdIntsLib { using SafeMathIntLib for int256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Discount { int256 tier; int256 value; } struct Entry { uint256 blockNumber; int256 nominal; Discount[] discounts; } struct BlockNumbDisdInts { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentNominalValue(BlockNumbDisdInts storage self) internal view returns (int256) { return nominalValueAt(self, block.number); } function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier) internal view returns (int256) { return discountedValueAt(self, block.number, tier); } function currentEntry(BlockNumbDisdInts storage self) internal view returns (Entry) { return entryAt(self, block.number); } function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber) internal view returns (int256) { return entryAt(self, _blockNumber).nominal; } function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier) internal view returns (int256) { Entry memory entry = entryAt(self, _blockNumber); if (0 < entry.discounts.length) { uint256 index = indexByTier(entry.discounts, tier); if (0 < index) return entry.nominal.mul( ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value) ).div( ConstantsLib.PARTS_PER() ); else return entry.nominal; } else return entry.nominal; } function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber) internal view returns (Entry) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.length++; Entry storage entry = self.entries[self.entries.length - 1]; entry.blockNumber = blockNumber; entry.nominal = nominal; } function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) internal { require(discountTiers.length == discountValues.length); addNominalEntry(self, blockNumber, nominal); Entry storage entry = self.entries[self.entries.length - 1]; for (uint256 i = 0; i < discountTiers.length; i++) entry.discounts.push(Discount(discountTiers[i], discountValues[i])); } function count(BlockNumbDisdInts storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbDisdInts storage self) internal view returns (Entry[]) { return self.entries; } function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } /// @dev The index returned here is 1-based function indexByTier(Discount[] discounts, int256 tier) internal pure returns (uint256) { require(0 < discounts.length); for (uint256 i = discounts.length; i > 0; i--) if (tier >= discounts[i - 1].tier) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title MonetaryTypesLib * @dev Monetary data types */ library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbReferenceCurrenciesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; MonetaryTypesLib.Currency currency; } struct BlockNumbReferenceCurrencies { mapping(address => mapping(uint256 => Entry[])) entriesByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (MonetaryTypesLib.Currency storage) { return currencyAt(self, referenceCurrency, block.number); } function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (Entry storage) { return entryAt(self, referenceCurrency, block.number); } function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 _blockNumber) internal view returns (MonetaryTypesLib.Currency storage) { return entryAt(self, referenceCurrency, _blockNumber).currency; } function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 _blockNumber) internal view returns (Entry storage) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)]; } function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber, MonetaryTypesLib.Currency referenceCurrency, MonetaryTypesLib.Currency currency) internal { require( 0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length || blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber ); self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency)); } function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (uint256) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length; } function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency) internal view returns (Entry[] storage) { return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id]; } function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length); for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--) if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library BlockNumbFiguresLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Entry { uint256 blockNumber; MonetaryTypesLib.Figure value; } struct BlockNumbFigures { Entry[] entries; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function currentValue(BlockNumbFigures storage self) internal view returns (MonetaryTypesLib.Figure storage) { return valueAt(self, block.number); } function currentEntry(BlockNumbFigures storage self) internal view returns (Entry storage) { return entryAt(self, block.number); } function valueAt(BlockNumbFigures storage self, uint256 _blockNumber) internal view returns (MonetaryTypesLib.Figure storage) { return entryAt(self, _blockNumber).value; } function entryAt(BlockNumbFigures storage self, uint256 _blockNumber) internal view returns (Entry storage) { return self.entries[indexByBlockNumber(self, _blockNumber)]; } function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure value) internal { require( 0 == self.entries.length || blockNumber > self.entries[self.entries.length - 1].blockNumber ); self.entries.push(Entry(blockNumber, value)); } function count(BlockNumbFigures storage self) internal view returns (uint256) { return self.entries.length; } function entries(BlockNumbFigures storage self) internal view returns (Entry[] storage) { return self.entries; } function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber) internal view returns (uint256) { require(0 < self.entries.length); for (uint256 i = self.entries.length - 1; i >= 0; i--) if (blockNumber >= self.entries[i].blockNumber) return i; revert(); } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Configuration * @notice An oracle for configurations values */ contract Configuration is Modifiable, Ownable, Servable { using SafeMathIntLib for int256; using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints; using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts; using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts; using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies; using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public OPERATIONAL_MODE_ACTION = "operational_mode"; // // Enums // ----------------------------------------------------------------------------------------------------------------- enum OperationalMode {Normal, Exit} // // Variables // ----------------------------------------------------------------------------------------------------------------- OperationalMode public operationalMode = OperationalMode.Normal; BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber; BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber; BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber; mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber; BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber; mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber; BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber; BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber; BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber; BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber; BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber; BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber; uint256 public earliestSettlementBlockNumber; bool public earliestSettlementBlockNumberUpdateDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetOperationalModeExitEvent(); event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks); event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks); event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal, int256[] discountTiers, int256[] discountValues); event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal); event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal); event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId, address feeCurrencyCt, uint256 feeCurrencyId); event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds); event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt, uint256 stakeCurrencyId); event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction); event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber); event DisableEarliestSettlementBlockNumberUpdateEvent(); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { updateDelayBlocksByBlockNumber.addEntry(block.number, 0); } // // Public functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set operational mode to Exit /// @dev Once operational mode is set to Exit it may not be set back to Normal function setOperationalModeExit() public onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION) { operationalMode = OperationalMode.Exit; emit SetOperationalModeExitEvent(); } /// @notice Return true if operational mode is Normal function isOperationalModeNormal() public view returns (bool) { return OperationalMode.Normal == operationalMode; } /// @notice Return true if operational mode is Exit function isOperationalModeExit() public view returns (bool) { return OperationalMode.Exit == operationalMode; } /// @notice Get the current value of update delay blocks /// @return The value of update delay blocks function updateDelayBlocks() public view returns (uint256) { return updateDelayBlocksByBlockNumber.currentValue(); } /// @notice Get the count of update delay blocks values /// @return The count of update delay blocks values function updateDelayBlocksCount() public view returns (uint256) { return updateDelayBlocksByBlockNumber.count(); } /// @notice Set the number of update delay blocks /// @param fromBlockNumber Block number from which the update applies /// @param newUpdateDelayBlocks The new update delay blocks value function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks); emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks); } /// @notice Get the current value of confirmation blocks /// @return The value of confirmation blocks function confirmationBlocks() public view returns (uint256) { return confirmationBlocksByBlockNumber.currentValue(); } /// @notice Get the count of confirmation blocks values /// @return The count of confirmation blocks values function confirmationBlocksCount() public view returns (uint256) { return confirmationBlocksByBlockNumber.count(); } /// @notice Set the number of confirmation blocks /// @param fromBlockNumber Block number from which the update applies /// @param newConfirmationBlocks The new confirmation blocks value function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks); emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks); } /// @notice Get number of trade maker fee block number tiers function tradeMakerFeesCount() public view returns (uint256) { return tradeMakerFeeByBlockNumber.count(); } /// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function tradeMakerFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of trade taker fee block number tiers function tradeTakerFeesCount() public view returns (uint256) { return tradeTakerFeeByBlockNumber.count(); } /// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function tradeTakerFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of payment fee block number tiers function paymentFeesCount() public view returns (uint256) { return paymentFeeByBlockNumber.count(); } /// @notice Get payment relative fee at given block number, possibly discounted by discount tier value /// @param blockNumber The concerned block number /// @param discountTier The concerned discount tier function paymentFee(uint256 blockNumber, int256 discountTier) public view returns (int256) { return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier); } /// @notice Set payment nominal relative fee and discount tiers and values at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues); emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues); } /// @notice Get number of payment fee block number tiers of given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentFeesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count(); } /// @notice Get payment relative fee for given currency at given block number, possibly discounted by /// discount tier value /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param discountTier The concerned discount tier function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier) public view returns (int256) { if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count()) return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt( blockNumber, discountTier ); else return paymentFee(blockNumber, discountTier); } /// @notice Set payment nominal relative fee and discount tiers and values for given currency at given /// block number tier /// @param fromBlockNumber Block number from which the update applies /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param nominal Nominal relative fee /// @param nominal Discount tier levels /// @param nominal Discount values function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal, int256[] discountTiers, int256[] discountValues) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry( fromBlockNumber, nominal, discountTiers, discountValues ); emit SetCurrencyPaymentFeeEvent( fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues ); } /// @notice Get number of minimum trade maker fee block number tiers function tradeMakerMinimumFeesCount() public view returns (uint256) { return tradeMakerMinimumFeeByBlockNumber.count(); } /// @notice Get trade maker minimum relative fee at given block number /// @param blockNumber The concerned block number function tradeMakerMinimumFee(uint256 blockNumber) public view returns (int256) { return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set trade maker minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum trade taker fee block number tiers function tradeTakerMinimumFeesCount() public view returns (uint256) { return tradeTakerMinimumFeeByBlockNumber.count(); } /// @notice Get trade taker minimum relative fee at given block number /// @param blockNumber The concerned block number function tradeTakerMinimumFee(uint256 blockNumber) public view returns (int256) { return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set trade taker minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum payment fee block number tiers function paymentMinimumFeesCount() public view returns (uint256) { return paymentMinimumFeeByBlockNumber.count(); } /// @notice Get payment minimum relative fee at given block number /// @param blockNumber The concerned block number function paymentMinimumFee(uint256 blockNumber) public view returns (int256) { return paymentMinimumFeeByBlockNumber.valueAt(blockNumber); } /// @notice Set payment minimum relative fee at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param nominal Minimum relative fee function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal); emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal); } /// @notice Get number of minimum payment fee block number tiers for given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count(); } /// @notice Get payment minimum relative fee for given currency at given block number /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId) public view returns (int256) { if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count()) return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber); else return paymentMinimumFee(blockNumber); } /// @notice Set payment minimum relative fee for given currency at given block number tier /// @param fromBlockNumber Block number from which the update applies /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param nominal Minimum relative fee function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal); emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal); } /// @notice Get number of fee currencies for the given reference currency /// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20) function feeCurrenciesCount(address currencyCt, uint256 currencyId) public view returns (uint256) { return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId)); } /// @notice Get the fee currency for the given reference currency at given block number /// @param blockNumber The concerned block number /// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20) function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId) public view returns (address ct, uint256 id) { MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt( MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber ); ct = _feeCurrency.ct; id = _feeCurrency.id; } /// @notice Set the fee currency for the given reference currency at given block number /// @param fromBlockNumber Block number from which the update applies /// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH) /// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20) /// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH) /// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20) function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId, address feeCurrencyCt, uint256 feeCurrencyId) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { feeCurrencyByCurrencyBlockNumber.addEntry( fromBlockNumber, MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId), MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId) ); emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId, feeCurrencyCt, feeCurrencyId); } /// @notice Get the current value of wallet lock timeout /// @return The value of wallet lock timeout function walletLockTimeout() public view returns (uint256) { return walletLockTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of wallet lock /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of cancel order challenge timeout /// @return The value of cancel order challenge timeout function cancelOrderChallengeTimeout() public view returns (uint256) { return cancelOrderChallengeTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of cancel order challenge /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of settlement challenge timeout /// @return The value of settlement challenge timeout function settlementChallengeTimeout() public view returns (uint256) { return settlementChallengeTimeoutByBlockNumber.currentValue(); } /// @notice Set timeout of settlement challenges /// @param fromBlockNumber Block number from which the update applies /// @param timeoutInSeconds Timeout duration in seconds function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds); emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds); } /// @notice Get the current value of fraud stake fraction /// @return The value of fraud stake fraction function fraudStakeFraction() public view returns (uint256) { return fraudStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in fraud challenge /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of wallet settlement stake fraction /// @return The value of wallet settlement stake fraction function walletSettlementStakeFraction() public view returns (uint256) { return walletSettlementStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in settlement challenge triggered by wallet /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of operator settlement stake fraction /// @return The value of operator settlement stake fraction function operatorSettlementStakeFraction() public view returns (uint256) { return operatorSettlementStakeFractionByBlockNumber.currentValue(); } /// @notice Set fraction of security bond that will be gained from successfully challenging /// in settlement challenge triggered by operator /// @param fromBlockNumber Block number from which the update applies /// @param stakeFraction The fraction gained function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction); emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction); } /// @notice Get the current value of operator settlement stake /// @return The value of operator settlement stake function operatorSettlementStake() public view returns (int256 amount, address currencyCt, uint256 currencyId) { MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue(); amount = stake.amount; currencyCt = stake.currency.ct; currencyId = stake.currency.id; } /// @notice Set figure of security bond that will be gained from successfully challenging /// in settlement challenge triggered by operator /// @param fromBlockNumber Block number from which the update applies /// @param stakeAmount The amount gained /// @param stakeCurrencyCt The address of currency gained /// @param stakeCurrencyId The ID of currency gained function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt, uint256 stakeCurrencyId) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber) { MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId)); operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake); emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId); } /// @notice Set the block number of the earliest settlement initiation /// @param _earliestSettlementBlockNumber The block number of the earliest settlement function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber) public onlyOperator { earliestSettlementBlockNumber = _earliestSettlementBlockNumber; emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber); } /// @notice Disable further updates to the earliest settlement block number /// @dev This operation can not be undone function disableEarliestSettlementBlockNumberUpdate() public onlyOperator { earliestSettlementBlockNumberUpdateDisabled = true; emit DisableEarliestSettlementBlockNumberUpdateEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDelayedBlockNumber(uint256 blockNumber) { require( 0 == updateDelayBlocksByBlockNumber.count() || blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue() ); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Benefactor * @notice An ownable that has a client fund property */ contract Configurable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- Configuration public configuration; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the configuration contract /// @param newConfiguration The (address of) Configuration contract instance function setConfiguration(Configuration newConfiguration) public onlyDeployer notNullAddress(newConfiguration) notSameAddresses(newConfiguration, configuration) { // Set new configuration Configuration oldConfiguration = configuration; configuration = newConfiguration; // Emit event emit SetConfigurationEvent(oldConfiguration, newConfiguration); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier configurationInitialized() { require(configuration != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library */ /** * @title SafeMathUintLib * @dev Math operations with safety checks that throw on error */ library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency) { require(index < self.currencies.length); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[]) { require(0 < self.currencies.length); require(low <= up); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ library NonFungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256[] ids; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256[])) idsByCurrency; mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[]) { return self.idsByCurrency[currencyCt][currencyId]; } function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) internal view returns (int256[]) { if (0 == self.idsByCurrency[currencyCt][currencyId].length) return new int256[](0); indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1); int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1); for (uint256 i = indexLow; i < indexUp; i++) idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i]; return idsByCurrency; } function idsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.idsByCurrency[currencyCt][currencyId].length; } function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 < self.idIndexById[currencyCt][currencyId][id]; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256[], uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256[], uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.ids, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[], uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.ids, record.blockNumber); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal { int256[] memory ids = new int256[](1); ids[0] = id; set(self, ids, currencyCt, currencyId); } function set(Balance storage self, int256[] ids, address currencyCt, uint256 currencyId) internal { uint256 i; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId] = ids; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function reset(Balance storage self, address currencyCt, uint256 currencyId) internal { for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId].length = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { if (0 < self.idIndexById[currencyCt][currencyId][id]) return false; self.idsByCurrency[currencyCt][currencyId].push(id); self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { uint256 index = self.idIndexById[currencyCt][currencyId][id]; if (0 == index) return false; if (index < self.idsByCurrency[currencyCt][currencyId].length) { self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1]; self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index; } self.idsByCurrency[currencyCt][currencyId].length--; self.idIndexById[currencyCt][currencyId][id] = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function transfer(Balance storage _from, Balance storage _to, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title Balance tracker * @notice An ownable to track balances of generic types */ contract BalanceTracker is Ownable, Servable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using FungibleBalanceLib for FungibleBalanceLib.Balance; using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public DEPOSITED_BALANCE_TYPE = "deposited"; string constant public SETTLED_BALANCE_TYPE = "settled"; string constant public STAGED_BALANCE_TYPE = "staged"; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Wallet { mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType; mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType; } // // Variables // ----------------------------------------------------------------------------------------------------------------- bytes32 public depositedBalanceType; bytes32 public settledBalanceType; bytes32 public stagedBalanceType; bytes32[] public _allBalanceTypes; bytes32[] public _activeBalanceTypes; bytes32[] public trackedBalanceTypes; mapping(bytes32 => bool) public trackedBalanceTypeMap; mapping(address => Wallet) private walletMap; address[] public trackedWallets; mapping(address => uint256) public trackedWalletIndexByWallet; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE)); settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE)); stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE)); _allBalanceTypes.push(settledBalanceType); _allBalanceTypes.push(depositedBalanceType); _allBalanceTypes.push(stagedBalanceType); _activeBalanceTypes.push(settledBalanceType); _activeBalanceTypes.push(depositedBalanceType); } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the fungible balance (amount) of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The stored balance function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256) { return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId); } /// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param indexLow The lower index of IDs /// @param indexUp The upper index of IDs /// @return The stored balance function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) public view returns (int256[]) { return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices( currencyCt, currencyId, indexLow, indexUp ); } /// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The stored balance function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[]) { return walletMap[wallet].nonFungibleBalanceByType[_type].get( currencyCt, currencyId ); } /// @notice Get the count of non-fungible IDs of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of IDs function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount( currencyCt, currencyId ); } /// @notice Gauge whether the ID is included in the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param id The ID of the concerned unit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if ID is included, else false function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].nonFungibleBalanceByType[_type].hasId( id, currencyCt, currencyId ); } /// @notice Set the balance of the given wallet, type and currency to the given value /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to set /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if setting fungible balance, else false function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].set( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].set( value, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param ids The ids of non-fungible) to set /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function setIds(address wallet, bytes32 _type, int256[] ids, address currencyCt, uint256 currencyId) public onlyActiveService { // Update the balance walletMap[wallet].nonFungibleBalanceByType[_type].set( ids, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Add the given value to the balance of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to add /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if adding fungible balance, else false function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].add( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].add( value, currencyCt, currencyId ); // Update balance type hashes _updateTrackedBalanceTypes(_type); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Subtract the given value from the balance of the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param value The value (amount of fungible, id of non-fungible) to subtract /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param fungible True if subtracting fungible balance, else false function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { // Update the balance if (fungible) walletMap[wallet].fungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); // Update tracked wallets _updateTrackedWallets(wallet); } /// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if data is stored, else false function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId); } /// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return true if data is stored, else false function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId); } /// @notice Get the count of fungible balance records for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of balance log entries function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } /// @notice Get the fungible balance record for the given wallet, type, currency /// log entry index /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param index The concerned record index /// @return The balance record function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// block number /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param _blockNumber The concerned block number /// @return The balance record function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } /// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The last log entry function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } /// @notice Get the count of non-fungible balance records for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The count of balance log entries function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// and record index /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param index The concerned record index /// @return The balance record function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } /// @notice Get the non-fungible balance record for the given wallet, type, currency /// and block number /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param _blockNumber The concerned block number /// @return The balance record function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } /// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency /// @param wallet The address of the concerned wallet /// @param _type The balance type /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The last log entry function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } /// @notice Get the count of tracked balance types /// @return The count of tracked balance types function trackedBalanceTypesCount() public view returns (uint256) { return trackedBalanceTypes.length; } /// @notice Get the count of tracked wallets /// @return The count of tracked wallets function trackedWalletsCount() public view returns (uint256) { return trackedWallets.length; } /// @notice Get the default full set of balance types /// @return The set of all balance types function allBalanceTypes() public view returns (bytes32[]) { return _allBalanceTypes; } /// @notice Get the default set of active balance types /// @return The set of active balance types function activeBalanceTypes() public view returns (bytes32[]) { return _activeBalanceTypes; } /// @notice Get the subset of tracked wallets in the given index range /// @param low The lower index /// @param up The upper index /// @return The subset of tracked wallets function trackedWalletsByIndices(uint256 low, uint256 up) public view returns (address[]) { require(0 < trackedWallets.length); require(low <= up); up = up.clampMax(trackedWallets.length - 1); address[] memory _trackedWallets = new address[](up - low + 1); for (uint256 i = low; i <= up; i++) _trackedWallets[i - low] = trackedWallets[i]; return _trackedWallets; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _updateTrackedBalanceTypes(bytes32 _type) private { if (!trackedBalanceTypeMap[_type]) { trackedBalanceTypeMap[_type] = true; trackedBalanceTypes.push(_type); } } function _updateTrackedWallets(address wallet) private { if (0 == trackedWalletIndexByWallet[wallet]) { trackedWallets.push(wallet); trackedWalletIndexByWallet[wallet] = trackedWallets.length; } } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title BalanceTrackable * @notice An ownable that has a balance tracker property */ contract BalanceTrackable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- BalanceTracker public balanceTracker; bool public balanceTrackerFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker); event FreezeBalanceTrackerEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the balance tracker contract /// @param newBalanceTracker The (address of) BalanceTracker contract instance function setBalanceTracker(BalanceTracker newBalanceTracker) public onlyDeployer notNullAddress(newBalanceTracker) notSameAddresses(newBalanceTracker, balanceTracker) { // Require that this contract has not been frozen require(!balanceTrackerFrozen); // Update fields BalanceTracker oldBalanceTracker = balanceTracker; balanceTracker = newBalanceTracker; // Emit event emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker); } /// @notice Freeze the balance tracker from further updates /// @dev This operation can not be undone function freezeBalanceTracker() public onlyDeployer { balanceTrackerFrozen = true; // Emit event emit FreezeBalanceTrackerEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier balanceTrackerInitialized() { require(balanceTracker != address(0)); _; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NahmiiTypesLib * @dev Data types of general nahmii character */ library NahmiiTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum ChallengePhase {Dispute, Closed} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OriginFigure { uint256 originId; MonetaryTypesLib.Figure figure; } struct IntendedConjugateCurrency { MonetaryTypesLib.Currency intended; MonetaryTypesLib.Currency conjugate; } struct SingleFigureTotalOriginFigures { MonetaryTypesLib.Figure single; OriginFigure[] total; } struct TotalOriginFigures { OriginFigure[] total; } struct CurrentPreviousInt256 { int256 current; int256 previous; } struct SingleTotalInt256 { int256 single; int256 total; } struct IntendedConjugateCurrentPreviousInt256 { CurrentPreviousInt256 intended; CurrentPreviousInt256 conjugate; } struct IntendedConjugateSingleTotalInt256 { SingleTotalInt256 intended; SingleTotalInt256 conjugate; } struct WalletOperatorHashes { bytes32 wallet; bytes32 operator; } struct Signature { bytes32 r; bytes32 s; uint8 v; } struct Seal { bytes32 hash; Signature signature; } struct WalletOperatorSeal { Seal wallet; Seal operator; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title SettlementChallengeTypesLib * @dev Types for settlement challenges */ library SettlementChallengeTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- enum Status {Qualified, Disqualified} struct Proposal { address wallet; uint256 nonce; uint256 referenceBlockNumber; uint256 definitionBlockNumber; uint256 expirationTime; // Status Status status; // Amounts Amounts amounts; // Currency MonetaryTypesLib.Currency currency; // Info on challenged driip Driip challenged; // True is equivalent to reward coming from wallet's balance bool walletInitiated; // True if proposal has been terminated bool terminated; // Disqualification Disqualification disqualification; } struct Amounts { // Cumulative (relative) transfer info int256 cumulativeTransfer; // Stage info int256 stage; // Balances after amounts have been staged int256 targetBalance; } struct Driip { // Kind ("payment", "trade", ...) string kind; // Hash (of operator) bytes32 hash; } struct Disqualification { // Challenger address challenger; uint256 nonce; uint256 blockNumber; // Info on candidate driip Driip candidate; } } /* * Hubii Nahmii * * Compliant with the Hubii Nahmii specification v0.12. * * Copyright (C) 2017-2018 Hubii AS */ /** * @title NullSettlementChallengeState * @notice Where null settlements challenge state is managed */ contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal"; string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal"; string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal"; string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal"; // // Variables // ----------------------------------------------------------------------------------------------------------------- SettlementChallengeTypesLib.Proposal[] public proposals; mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated); event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the number of proposals /// @return The number of proposals function proposalsCount() public view returns (uint256) { return proposals.length; } /// @notice Initiate a proposal /// @param wallet The address of the concerned challenged wallet /// @param nonce The wallet nonce /// @param stageAmount The proposal stage amount /// @param targetBalanceAmount The proposal target balance amount /// @param currency The concerned currency /// @param blockNumber The proposal block number /// @param walletInitiated True if initiated by the concerned challenged wallet function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated) public onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION) { // Initiate proposal _initiateProposal( wallet, nonce, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated ); // Emit event emit InitiateProposalEvent( wallet, nonce, stageAmount, targetBalanceAmount, currency, blockNumber, walletInitiated ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function terminateProposal(address wallet, MonetaryTypesLib.Currency currency) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); } /// @notice Terminate a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function terminateProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated) public onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to terminate if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated); // Terminate proposal proposals[index - 1].terminated = true; // Emit event emit TerminateProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency function removeProposal(address wallet, MonetaryTypesLib.Currency currency) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); // Remove proposal _removeProposal(index); } /// @notice Remove a proposal /// @param wallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param walletTerminated True if wallet terminated function removeProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated) public onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Return gracefully if there is no proposal to remove if (0 == index) return; // Require that role that initialized (wallet or operator) can only cancel its own proposal require(walletTerminated == proposals[index - 1].walletInitiated); // Emit event emit RemoveProposalEvent( wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated ); // Remove proposal _removeProposal(index); } /// @notice Disqualify a proposal /// @dev A call to this function will intentionally override previous disqualifications if existent /// @param challengedWallet The address of the concerned challenged wallet /// @param currency The concerned currency /// @param challengerWallet The address of the concerned challenger wallet /// @param blockNumber The disqualification block number /// @param candidateNonce The candidate nonce /// @param candidateHash The candidate hash /// @param candidateKind The candidate kind function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency currency, address challengerWallet, uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string candidateKind) public onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION) { // Get the proposal index uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id]; require(0 != index); // Update proposal proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].disqualification.challenger = challengerWallet; proposals[index - 1].disqualification.nonce = candidateNonce; proposals[index - 1].disqualification.blockNumber = blockNumber; proposals[index - 1].disqualification.candidate.hash = candidateHash; proposals[index - 1].disqualification.candidate.kind = candidateKind; // Emit event emit DisqualifyProposalEvent( challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind ); } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposal(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { // 1-based index return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; } /// @notice Gauge whether the proposal for the given wallet and currency has terminated /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has terminated, else false function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].terminated; } /// @notice Gauge whether the proposal for the given wallet and currency has expired /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return true if proposal has expired, else false function hasProposalExpired(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { // 1-based index uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return block.timestamp >= proposals[index - 1].expirationTime; } /// @notice Get the settlement proposal challenge nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal nonce function proposalNonce(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].nonce; } /// @notice Get the settlement proposal reference block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].referenceBlockNumber; } /// @notice Get the settlement proposal definition block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal reference block number function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].definitionBlockNumber; } /// @notice Get the settlement proposal expiration time of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal expiration time function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].expirationTime; } /// @notice Get the settlement proposal status of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal status function proposalStatus(address wallet, MonetaryTypesLib.Currency currency) public view returns (SettlementChallengeTypesLib.Status) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].status; } /// @notice Get the settlement proposal stage amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal stage amount function proposalStageAmount(address wallet, MonetaryTypesLib.Currency currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].amounts.stage; } /// @notice Get the settlement proposal target balance amount of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal target balance amount function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency currency) public view returns (int256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].amounts.targetBalance; } /// @notice Get the settlement proposal balance reward of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal balance reward function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency currency) public view returns (bool) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].walletInitiated; } /// @notice Get the settlement proposal disqualification challenger of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification challenger function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency currency) public view returns (address) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.challenger; } /// @notice Get the settlement proposal disqualification block number of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification block number function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.blockNumber; } /// @notice Get the settlement proposal disqualification nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification nonce function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.nonce; } /// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate hash function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency currency) public view returns (bytes32) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.candidate.hash; } /// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The settlement proposal disqualification candidate kind function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency currency) public view returns (string) { uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; require(0 != index); return proposals[index - 1].disqualification.candidate.kind; } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 referenceBlockNumber, bool walletInitiated) private { // Require that stage and target balance amounts are positive require(stageAmount.isPositiveInt256()); require(targetBalanceAmount.isPositiveInt256()); uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id]; // Create proposal if needed if (0 == index) { index = ++(proposals.length); proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index; } // Populate proposal proposals[index - 1].wallet = wallet; proposals[index - 1].nonce = nonce; proposals[index - 1].referenceBlockNumber = referenceBlockNumber; proposals[index - 1].definitionBlockNumber = block.number; proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout()); proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified; proposals[index - 1].currency = currency; proposals[index - 1].amounts.stage = stageAmount; proposals[index - 1].amounts.targetBalance = targetBalanceAmount; proposals[index - 1].walletInitiated = walletInitiated; proposals[index - 1].terminated = false; } function _removeProposal(uint256 index) private returns (bool) { // Remove the proposal and clear references to it proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0; if (index < proposals.length) { proposals[index - 1] = proposals[proposals.length - 1]; proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index; } proposals.length--; } function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId) private view returns (int256 amount, uint256 blockNumber) { // Get last log record of deposited and settled balances (int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord( wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId ); (int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord( wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId ); // Set amount as the sum of deposited and settled amount = depositedAmount.add(settledAmount); // Set block number as the latest of deposited and settled blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber; } }
Enable a named action in a service contract service The address of the service contract action The name of the action to be disabled Emit event
function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; emit DisableServiceActionEvent(service, action); }
415,201
/* ███████╗████████╗██╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ███╗ ██╔════╝╚══██╔══╝██║ ██║██╔════╝██╔══██╗██╔════╝██║ ██║████╗ ████║ █████╗ ██║ ███████║█████╗ ██████╔╝█████╗ ██║ ██║██╔████╔██║ ██╔══╝ ██║ ██╔══██║██╔══╝ ██╔══██╗██╔══╝ ██║ ██║██║╚██╔╝██║ ███████╗ ██║ ██║ ██║███████╗██║ ██║███████╗╚██████╔╝██║ ╚═╝ ██║ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ___ _ _ _ ( _`\ ( )_ ( )_ ( )_ | | ) | _ _ | ,_) _ _ ___ _ ___ | ,_) _ __ _ _ ___ | ,_) | | | ) /'_` )| | /'_` ) /'___) /'_`\ /' _ `\| | ( '__)/'_` ) /'___)| | | |_) |( (_| || |_ ( (_| | ( (___ ( (_) )| ( ) || |_ | | ( (_| |( (___ | |_ (____/'`\__,_)`\__)`\__,_) `\____)`\___/'(_) (_)`\__)(_) `\__,_)`\____)`\__) */ pragma solidity ^0.4.25; // Tested on version 0.4.25 /* * Use this interface to take the Logic contract address from proxy contract. */ contract ProxyInterface { function getLogicContractAddress() public view returns (address); function getAutoMatchContractAddress() public view returns (address); } contract DataContract { /* ******************** CONTRACT INFORMATION ******************** * This contract holds the Data of the platform. * * The methods can be called only from Logic contract, * so there are not many checks done here. */ /* * Initialize with proxy contract address. */ address private proxyAddress; constructor(address _proxyAddress) public { proxyAddress = _proxyAddress; } /* * Get Logic contract address from the proxy contract. */ function getLogicContractAddress() private view returns (address) { return ProxyInterface(proxyAddress).getLogicContractAddress(); } /* * Get Auto Match contract address from the proxy contract. */ function getAutoMatchContractAddress() private view returns (address) { return ProxyInterface(proxyAddress).getAutoMatchContractAddress(); } /* * Set modifier so public functions can be called only from the * Logic contract and not from any other contract. */ modifier onlyLogicContract { require(msg.sender == getLogicContractAddress() || msg.sender == getAutoMatchContractAddress()); _; } /* ******************** USER INFORMATION ******************** * We need a struct that will keep information about the orders of each user. * By using a mapping we can easy find all the orders of a specific user. * * @openOrdersAmount keep the total amount of open orders of this user. * @matchedOrdersAmount keep the total amount of matched orders of this user. * @storeOfValueOpenOrders keep the unique ID's of "Store of Value" open orders of this user. * @increasePriceOpenOrders keep the unique ID's of "Price increase bet" open orders of this user. * @matchedOrders keep the unique ID's of all matched orders of this user. */ struct User { uint128 openOrdersAmount; uint128 matchedOrdersAmount; uint[] storeOfValueOpenOrders; uint[] increasePriceOpenOrders; uint[] matchedOrders; } mapping(address => User) private users; /* * This function edits the [openOrdersAmount] and [matchedOrdersAmount] of a specific user. * * @_user is the address of the user. * @_newAmount is the new value of the amount for this user. * @_openOrder selects if we refer to an open order (True) or to a matched order (False) */ function editOrdersAmount(address _user, uint128 _newAmount, bool _openOrder) external onlyLogicContract payable returns(bool) { // Edit openOrdersAmount if (_openOrder) { users[_user].openOrdersAmount = _newAmount; return true; } // Edit matchedOrdersAmount else { users[_user].matchedOrdersAmount = _newAmount; return true; } } /* * Adds or deletes element from [storeOfValueOpenOrders], [increasePriceOpenOrders] and [matchedOrders]. * * @_user is the address of the user. * @_push adds/push a new element (True) or deletes an existing element (False). * @_openOrder refers to an open order (True) or to a matched order (False). * @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False). * @_number refers to the order number/ID. */ function editOrdersArray(address _user, bool _push, bool _openOrder, bool _storeOfValue, uint _number) external onlyLogicContract payable returns(bool) { // Push new order to storeOfValueOpenOrders if (_push == true && _openOrder == true && _storeOfValue == true) { users[_user].storeOfValueOpenOrders.push(_number); return true; } // Push new order to increasePriceOpenOrders else if (_push == true && _openOrder == true && _storeOfValue == false) { users[_user].increasePriceOpenOrders.push(_number); return true; } // Push new order to matchedOrders else if (_push == true && _openOrder == false) { users[_user].matchedOrders.push(_number); return true; } // Delete element from storeOfValueOpenOrders (by number) else if (_push == false && _openOrder == true && _storeOfValue == true) { return deleteArrayElement(users[_user].storeOfValueOpenOrders, _number); } // Delete element from increasePriceOpenOrders (by number) else if (_push == false && _openOrder == true && _storeOfValue == false) { return deleteArrayElement(users[_user].increasePriceOpenOrders, _number); } // Delete element from matchedOrders (by number) else if (_push == false && _openOrder == false) { return deleteArrayElement(users[_user].matchedOrders, _number); } return false; } /* * Getter returns the amount of open orders or matched orders of a specific user. * * @_user is the address of the user. * @_openOrder refers to an open order (True) or to a matched order (False). */ function getUserAmount(address _user, bool _openOrder) external onlyLogicContract view returns(uint128) { if (_openOrder) { return users[_user].openOrdersAmount; } else { return users[_user].matchedOrdersAmount; } } /* * Getter returns the ID's of the "Store of value" open orders of a specific user. * * @_user is the address of the user. */ function getUserStoreOfValueOpenOrders(address _user) external onlyLogicContract view returns(uint[]) { return users[_user].storeOfValueOpenOrders; } /* * Getter returns the ID's of the "Price increase bet" open orders of a specific user. * * @_user is the address of the user. */ function getUserPriceIncreaseOpenOrders(address _user) external onlyLogicContract view returns(uint[]) { return users[_user].increasePriceOpenOrders; } /* * Getter returns the ID's of the matched orders of a specific user. * * @_user is the address of the user. */ function getUserMatchedOrders(address _user) external onlyLogicContract view returns(uint[]) { return users[_user].matchedOrders; } /* * Getter returns the total amount of the orders and all orders ID's of a specific user. * * @_user is the address of the user. */ function returnUserInformation(address _user) external onlyLogicContract view returns(uint128, uint128, uint[], uint[], uint[]) { return(users[_user].openOrdersAmount, users[_user].matchedOrdersAmount, users[_user].storeOfValueOpenOrders, users[_user].increasePriceOpenOrders, users[_user].matchedOrders); } /* ******************** OPEN ORDERS ******************** * We need a struct that will keep information about open orders. * By using a mapping we can easy find the owner of a specific open order. * * @user is the address of the user that owns this open order. * @amount is the amount that user send for this open order. * @openOrdersStoreOfValue keeps the information of the user for each "Store of value" open order. * @openOrdersPriceIncrease keeps the information of the user for each "Price increase bet" open order. * @storeOfValueOrders keeps the active "Store of value" open orders. * @increaseValueOrders keep the active "Price increase bet" open orders. */ struct OpenOrder { address user; uint128 amount; } mapping(uint => OpenOrder) private openOrdersStoreOfValue; mapping(uint => OpenOrder) private openOrdersPriceIncrease; uint private openOrdersStoreOfValueIndex = 1; uint private openOrdersPriceIncreaseIndex = 1; uint[] private storeOfValueOrders; uint[] private increaseValueOrders; /* * Add a new open order from a user. * * @_user is the address of the user who makes this new order. * @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False). * @_amount is the amount that users sends to make this order. */ function addOpenOrder(address _user, bool _storeOfValue, uint128 _amount) external onlyLogicContract payable returns(uint) { // Create a "Store of Value" open order if (_storeOfValue) { openOrdersStoreOfValue[openOrdersStoreOfValueIndex].user = _user; openOrdersStoreOfValue[openOrdersStoreOfValueIndex].amount = _amount; storeOfValueOrders.push(openOrdersStoreOfValueIndex); openOrdersStoreOfValueIndex += 1; return openOrdersStoreOfValueIndex-1; } // Create a "Price increase bet" open order else { openOrdersPriceIncrease[openOrdersPriceIncreaseIndex].user = _user; openOrdersPriceIncrease[openOrdersPriceIncreaseIndex].amount = _amount; increaseValueOrders.push(openOrdersPriceIncreaseIndex); openOrdersPriceIncreaseIndex += 1; return openOrdersPriceIncreaseIndex-1; } } /* * Edits the amount of an open order. * * @_index is the ID of the order. * @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False). * @_amount is the new amount for this specific order. */ function editOpenOrder(uint _index, bool _storeOfValue, uint128 _amount) external onlyLogicContract payable returns(bool) { // Edit an existing "Store of value" order if (_storeOfValue) { openOrdersStoreOfValue[_index].amount = _amount; return true; } // Edit an existing "Price increase bet" order else { openOrdersPriceIncrease[_index].amount = _amount; return true; } return false; } /* * Removes the first element of the array and keeps their order. * * @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False). */ function removeOldestOpenOrder(bool _storeOfValue) external onlyLogicContract payable returns(bool) { // Remove the oldest "Store of Value" open order if (_storeOfValue == true) { if (storeOfValueOrders.length == 0) { return true; } for (uint i=0; i<storeOfValueOrders.length-1; i++) { storeOfValueOrders[i] = storeOfValueOrders[i+1]; } storeOfValueOrders.length--; return true; } // Remove the oldest "Price increase bet" open order else if (_storeOfValue == false) { if (increaseValueOrders.length == 0) { return true; } for (uint j=0; j<increaseValueOrders.length-1; j++) { increaseValueOrders[j] = increaseValueOrders[j+1]; } increaseValueOrders.length--; return true; } return false; } /* * Removes a spefific order ID. * * @_orderId is the ID of the order we want to remove. * @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False). */ function removeSpecificOpenOrder(uint _orderId, bool _storeOfValue) external onlyLogicContract payable returns(bool) { uint index = storeOfValueOrders.length; // Remove from "Store of Value" open orders if (_storeOfValue == true) { if (storeOfValueOrders[storeOfValueOrders.length-1] == _orderId) { storeOfValueOrders.length--; return true; } // Find index index = storeOfValueOrders.length; for (uint i=0; i<storeOfValueOrders.length; i++) { if (storeOfValueOrders[i] == _orderId) { index = i; break; } } // Check if element exists if (index == storeOfValueOrders.length) { return false; } for (i=index; i<storeOfValueOrders.length-1; i++) { storeOfValueOrders[i] = storeOfValueOrders[i+1]; } storeOfValueOrders.length--; return true; } // Remove from "Price increase bet" open orders else { if (increaseValueOrders[increaseValueOrders.length-1] == _orderId) { increaseValueOrders.length--; return true; } // Find index index = increaseValueOrders.length; for (uint j=0; j<increaseValueOrders.length; j++) { if (increaseValueOrders[j] == _orderId) { index = j; break; } } // Check if element exists if (index == increaseValueOrders.length) { return false; } for (j=index; j<increaseValueOrders.length-1; j++) { increaseValueOrders[j] ==increaseValueOrders[j+1]; } increaseValueOrders.length--; return true; } return false; } /* * Getter returns the information of a specific open order. * * @_orderId is the ID of the order we are looking for. * @_storeOfValue refers to a "Store of value" order (True) or to a "Price increase bet" order (False). */ function getUserOpenOrder(uint _orderId, bool _storeOfValue) external onlyLogicContract view returns(address, uint128) { bool check; if (_storeOfValue) { for (uint i=0; i<storeOfValueOrders.length; i++) { if (storeOfValueOrders[i] == _orderId) { check = true; } } require(check); return (openOrdersStoreOfValue[_orderId].user, openOrdersStoreOfValue[_orderId].amount); } else { for (uint j=0; j<increaseValueOrders.length; j++) { if (increaseValueOrders[j] == _orderId) { check = true; } } require(check); return (openOrdersPriceIncrease[_orderId].user, openOrdersPriceIncrease[_orderId].amount); } } /* * Getter of "Store of value" active orders. */ function getStoreOfValueOrders() external onlyLogicContract view returns(uint[]) { return storeOfValueOrders; } /* * Getter of "Increase value bet" active orders. */ function getIncreaseValueOrders() external onlyLogicContract view returns(uint[]) { return increaseValueOrders; } /* * Getter information of a specific "Store of valu" order. * * @_orderId is the ID of the order. */ function getStoreOfValueOrderInformation(uint _orderId) external onlyLogicContract view returns(address, uint128) { return (openOrdersStoreOfValue[_orderId].user, openOrdersStoreOfValue[_orderId].amount); } /* * Getter information of a specific "Increase value bet" order. * * @_orderId is the ID of the order. */ function getPriceIncreaseOrderInformation(uint _orderId) external onlyLogicContract view returns(address, uint128) { return (openOrdersPriceIncrease[_orderId].user, openOrdersPriceIncrease[_orderId].amount); } /* * Setter for changing the amount of a specific "Store of value" order. * * @_orderId is the ID of the order. * @_amount is the new amount. */ function decraseStoreOfValueBySpecificAmount(uint _orderId, uint128 _amount) external onlyLogicContract payable returns(bool) { openOrdersStoreOfValue[_orderId].amount -= _amount; return true; } /* * Setter for changing the amount of a specific "Increase price bet" order. * * @_orderId is the ID of the order. * @_amount is the new amount. */ function decraseIncreasePriceBySpecificAmount(uint _orderId, uint128 _amount) external onlyLogicContract payable returns(bool) { openOrdersPriceIncrease[_orderId].amount -= _amount; return true; } /* ******************** MATCHED ORDERS ******************** * We need a struct that will keep information about matched orders. * By using a mapping we can easy find information about a specific matched order. * * @userA is the address of the user with the "Store of value" position. * @userB is the address of the user with the "Price increase bet" position. * @amount is the amount of each user that send for this order (so, total amount = amount * 2). * @etherPrice is the Ether price when this matched order was made. * @active indicates if an order is active (True) or not (False). */ struct MatchedOrder { address userA; address userB; uint128 amount; uint32 etherPrice; bool active; } mapping(uint => MatchedOrder) private matchedOrders; /* * Add a new matched order. * * @_userA is the address of the user with the "Store of value" position. * @_userB is the address of the user with the "Price increase bet" position. * @_amount is the amount of each user that send for this order (so, total amount = amount * 2). * @_etherPrice is the Ether price when this matched order was made. */ function addMatchedOrder(address _userA, address _userB, uint128 _amount, uint32 _etherPrice) external onlyLogicContract payable returns(uint) { // Get a unique number and check that is available uint nonce = 0; uint orderId = uint(keccak256(abi.encodePacked(_userA,_userB,block.number,nonce))); while (matchedOrders[orderId].active == true) { nonce += 1; orderId = uint(keccak256(abi.encodePacked(_userA,_userB,block.number,nonce))); } // Add new elements matchedOrders[orderId].userA = _userA; matchedOrders[orderId].userB = _userB; matchedOrders[orderId].amount = _amount; matchedOrders[orderId].etherPrice = _etherPrice; matchedOrders[orderId].active = true; // Return the new matched order ID. return orderId; } /* * This function sends money to a specific user, during an order cancelation or completion. * * @_user is the address of the user we want to send the money to. * @_amount is the amount we want to send. */ function returnMoney(address _user, uint128 _amount) external onlyLogicContract payable returns(bool) { _user.transfer(uint256(_amount)); return true; } /* * Setter marks an order's ID as unused (canceled or completed order), so we can handle possible hash function collisions. * * @_orderId is the ID of the matched order. */ function disableMatchedOrder(uint _orderId) external onlyLogicContract payable returns(bool) { matchedOrders[_orderId].active = false; return true; } /* * Getter returns all the information about a specific matched order. * * @_orderId is the ID of the matched order. */ function getMatchedOrder(uint _orderId) external onlyLogicContract view returns(address, address, uint128, uint32, bool) { return(matchedOrders[_orderId].userA, matchedOrders[_orderId].userB, matchedOrders[_orderId].amount, matchedOrders[_orderId].etherPrice, matchedOrders[_orderId].active); } /* ******************** OTHER FUNCTIONS ******************** */ /* * This function removes a given array element. It doesn't keep the sorting of the array. * * @_array is the input array * @_id is the element value (not the index) that we want to remove. */ function deleteArrayElement(uint[] storage _array, uint _id) private returns(bool) { uint _index; if (_array.length == 1 || _array[_array.length-1] == _id) { _array.length--; return true; } else { for (uint i=0; i<_array.length; i++) { if (_array[i] == _id) { _index = i; _array[_index] = _array[_array.length-1]; _array.length--; return true; } } } return false; } /* * Getter returns the amount of a specific Store of Value open order. * * @_orderId is the ID of the order we want. */ function getStoreOfValueAmountByID(uint _orderId) public view returns(uint128) { require(msg.sender == openOrdersStoreOfValue[_orderId].user); return openOrdersStoreOfValue[_orderId].amount; } /* * Getter returns the amount of a specific Price Increase bet open order. * * @_orderId is the ID of the order we want. */ function getIncreasePriceAmountByID(uint _orderId) public view returns(uint128) { require(msg.sender == openOrdersPriceIncrease[_orderId].user); return openOrdersPriceIncrease[_orderId].amount; } /* * Getter returns the amount of a specific matched order. * * @_orderId is the ID of the order we want. */ function getMatchedOrderInformationtByID(uint _orderId) public view returns(uint128, bool, uint32) { require(msg.sender == matchedOrders[_orderId].userA || msg.sender == matchedOrders[_orderId].userB); if (msg.sender == matchedOrders[_orderId].userA) { return (matchedOrders[_orderId].amount, true, matchedOrders[_orderId].etherPrice); } else { return (matchedOrders[_orderId].amount, false, matchedOrders[_orderId].etherPrice); } } }
Getter returns the amount of a specific matched order. @_orderId is the ID of the order we want./
function getMatchedOrderInformationtByID(uint _orderId) public view returns(uint128, bool, uint32) { require(msg.sender == matchedOrders[_orderId].userA || msg.sender == matchedOrders[_orderId].userB); if (msg.sender == matchedOrders[_orderId].userA) { return (matchedOrders[_orderId].amount, true, matchedOrders[_orderId].etherPrice); return (matchedOrders[_orderId].amount, false, matchedOrders[_orderId].etherPrice); } }
917,176
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.2; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/utils/Utils.sol /** * @title Utilities Contract * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; contract Utils { /** MODIFIERS **/ /** * @notice Check if the address is not zero */ modifier onlyValidAddress(address _address) { require(_address != address(0), "Invalid address"); _; } /** * @notice Check if the address is not the sender's address */ modifier isSenderNot(address _address) { require(_address != msg.sender, "Address is the same as the sender"); _; } /** * @notice Check if the address is the sender's address */ modifier isSender(address _address) { require(_address == msg.sender, "Address is different from the sender"); _; } /** * @notice Controle if a boolean attribute (false by default) was updated to true. * @dev This attribute is designed specifically for recording an action. * @param criterion The boolean attribute that records if an action has taken place */ modifier onlyOnce(bool criterion) { require(criterion == false, "Already been set"); _; criterion = true; } } // File: contracts/utils/Managed.sol pragma solidity ^0.5.7; contract Managed is Utils, Ownable { // managers can be set and altered by owner, multiple manager accounts are possible mapping(address => bool) public isManager; /** EVENTS **/ event ChangedManager(address indexed manager, bool active); /*** MODIFIERS ***/ modifier onlyManager() { require(isManager[msg.sender], "not manager"); _; } /** * @dev Set / alter manager / whitelister "account". This can be done from owner only * @param manager address address of the manager to create/alter * @param active bool flag that shows if the manager account is active */ function setManager(address manager, bool active) public onlyOwner onlyValidAddress(manager) { isManager[manager] = active; emit ChangedManager(manager, active); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.2; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.2; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.2; contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol pragma solidity ^0.5.2; /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.2; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.2; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.2; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.2; /** * @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' require((value == 0) || (token.allowance(address(this), spender) == 0)); 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); 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 equal true). * @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. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } } // File: contracts/utils/Reclaimable.sol /** * @title Reclaimable * @dev This contract gives owner right to recover any ERC20 tokens accidentally sent to * the token contract. The recovered token will be sent to the owner of token. * @author Validity Labs AG <info@validitylabs.org> */ // solhint-disable-next-line compiler-fixed, compiler-gt-0_5 pragma solidity ^0.5.7; contract Reclaimable is Ownable { using SafeERC20 for IERC20; /** * @notice Let the owner to retrieve other tokens accidentally sent to this contract. * @dev This function is suitable when no token of any kind shall be stored under * the address of the inherited contract. * @param tokenToBeRecovered address of the token to be recovered. */ function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner { uint256 balance = tokenToBeRecovered.balanceOf(address(this)); tokenToBeRecovered.safeTransfer(msg.sender, balance); } } // File: openzeppelin-solidity/contracts/access/roles/WhitelistAdminRole.sol pragma solidity ^0.5.2; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender)); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol pragma solidity ^0.5.2; /** * @title WhitelistedRole * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove * it), and not Whitelisteds themselves. */ contract WhitelistedRole is WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(msg.sender)); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(msg.sender); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.2; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/token/ERC20/library/Snapshots.sol /** * @title Snapshot * @dev Utility library of the Snapshot structure, including getting value. * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; library Snapshots { using Math for uint256; using SafeMath for uint256; /** * @notice This structure stores the historical value associate at a particular timestamp * @param timestamp The timestamp of the creation of the snapshot * @param value The value to be recorded */ struct Snapshot { uint256 timestamp; uint256 value; } struct SnapshotList { Snapshot[] history; } /** TODO: within 1 block: transfer w/ snapshot, then dividend distrubtion, transfer w/ snapshot * * @notice This function creates snapshots for certain value... * @dev To avoid having two Snapshots with the same block.timestamp, we check if the last * existing one is the current block.timestamp, we update the last Snapshot * @param item The SnapshotList to be operated * @param _value The value associated the the item that is going to have a snapshot */ function createSnapshot(SnapshotList storage item, uint256 _value) internal { uint256 length = item.history.length; if (length == 0 || (item.history[length.sub(1)].timestamp < block.timestamp)) { item.history.push(Snapshot(block.timestamp, _value)); } else { // When the last existing snapshot is ready to be updated item.history[length.sub(1)].value = _value; } } /** * @notice Find the index of the item in the SnapshotList that contains information * corresponding to the timestamp. (FindLowerBond of the array) * @dev The binary search logic is inspired by the Arrays.sol from Openzeppelin * @param item The list of Snapshots to be queried * @param timestamp The timestamp of the queried moment * @return The index of the Snapshot array */ function findBlockIndex( SnapshotList storage item, uint256 timestamp ) internal view returns (uint256) { // Find lower bound of the array uint256 length = item.history.length; // Return value for extreme cases: If no snapshot exists and/or the last snapshot if (item.history[length.sub(1)].timestamp <= timestamp) { return length.sub(1); } else { // Need binary search for the value uint256 low = 0; uint256 high = length.sub(1); while (low < high.sub(1)) { uint256 mid = Math.average(low, high); // mid will always be strictly less than high and it rounds down if (item.history[mid].timestamp <= timestamp) { low = mid; } else { high = mid; } } return low; } } /** * @notice This function returns the value of the corresponding Snapshot * @param item The list of Snapshots to be queried * @param timestamp The timestamp of the queried moment * @return The value of the queried moment */ function getValueAt( SnapshotList storage item, uint256 timestamp ) internal view returns (uint256) { if (item.history.length == 0 || timestamp < item.history[0].timestamp) { return 0; } else { uint256 index = findBlockIndex(item, timestamp); return item.history[index].value; } } } // File: contracts/token/ERC20/ERC20Snapshot.sol /** * @title ERC20 Snapshot Token * @dev This is an ERC20 compatible token that takes snapshots of account balances. * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; contract ERC20Snapshot is ERC20 { using Snapshots for Snapshots.SnapshotList; mapping(address => Snapshots.SnapshotList) private _snapshotBalances; Snapshots.SnapshotList private _snapshotTotalSupply; event CreatedAccountSnapshot(address indexed account, uint256 indexed timestamp, uint256 value); event CreatedTotalSupplySnapshot(uint256 indexed timestamp, uint256 value); /** * @notice Return the historical supply of the token at a certain time * @param timestamp The block number of the moment when token supply is queried * @return The total supply at "timestamp" */ function totalSupplyAt(uint256 timestamp) public view returns (uint256) { return _snapshotTotalSupply.getValueAt(timestamp); } /** * @notice Return the historical balance of an account at a certain time * @param owner The address of the token holder * @param timestamp The block number of the moment when token supply is queried * @return The balance of the queried token holder at "timestamp" */ function balanceOfAt(address owner, uint256 timestamp) public view returns (uint256) { return _snapshotBalances[owner].getValueAt(timestamp); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @param from The address to transfer from * @param to The address to transfer to * @param value The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { super._transfer(from, to, value); // ERC20 transfer _createAccountSnapshot(from, balanceOf(from)); _createAccountSnapshot(to, balanceOf(to)); } /** OVERRIDE * @notice Mint tokens to one account while enforcing the update of Snapshots * @param account The address that receives tokens * @param value The amount of tokens to be created */ function _mint(address account, uint256 value) internal { super._mint(account, value); _createAccountSnapshot(account, balanceOf(account)); _createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).add(value)); } /** OVERRIDE * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal { super._burn(account, value); _createAccountSnapshot(account, balanceOf(account)); _createTotalSupplySnapshot(account, totalSupplyAt(block.timestamp).sub(value)); } /** * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { _snapshotTotalSupply.createSnapshot(amount); emit CreatedTotalSupplySnapshot(block.timestamp, amount); } /** * @notice creates an account snapshot & emits event * @param amount uint256 * @param account address */ function _createAccountSnapshot(address account, uint256 amount) internal { _snapshotBalances[account].createSnapshot(amount); emit CreatedAccountSnapshot(account, block.timestamp, amount); } function _precheckSnapshot() internal { // FILL LATER TODO: comment on how this is utilized // Why it's not being abstract } } // File: contracts/STO/token/WhitelistedSnapshot.sol /** * @title Whitelisted Snapshot Token * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; /** * Whitelisted Snapshot repurposes the following 2 variables inherited from ERC20Snapshot: * _snapshotBalances: only whitelisted accounts get snapshots * _snapshotTotalSupply: only the total sum of whitelisted */ contract WhitelistedSnapshot is ERC20Snapshot, WhitelistedRole { /** OVERRIDE * @notice add account to whitelist & create a snapshot of current balance * @param account address */ function addWhitelisted(address account) public { super.addWhitelisted(account); uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); uint256 newSupplyValue = totalSupplyAt(now).add(balance); _createTotalSupplySnapshot(account, newSupplyValue); } /** OVERRIDE * @notice remove account from white & create a snapshot of 0 balance * @param account address */ function removeWhitelisted(address account) public { super.removeWhitelisted(account); _createAccountSnapshot(account, 0); uint256 balance = balanceOf(account); uint256 newSupplyValue = totalSupplyAt(now).sub(balance); _createTotalSupplySnapshot(account, newSupplyValue); } /** OVERRIDE & call parent * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @dev the super._transfer call handles the snapshot of each account. See the internal functions * below: _createTotalSupplySnapshot & _createAccountSnapshot * @param from address The address to transfer from * @param to address The address to transfer to * @param value uint256 The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { // if available will call the sibiling's inherited function before calling the parent's super._transfer(from, to, value); /** * Possibilities: * Homogeneous Transfers: * 0: _whitelist to _whitelist: 0 total supply snapshot * 1: nonwhitelist to nonwhitelist: 0 total supply snapshot * Heterogeneous Transfers: * 2: _whitelist to nonwhitelist: 1 whitelisted total supply snapshot * 3: nonwhitelist to _whitelist: 1 whitelisted total supply snapshot */ // isWhitelistedHetero tells us to/from is a mix of whitelisted/not whitelisted accounts // isAdding tell us whether or not to add or subtract from the whitelisted total supply value (bool isWhitelistedHetero, bool isAdding) = _isWhitelistedHeterogeneousTransfer(from, to); if (isWhitelistedHetero) { // one account is whitelisted, the other is not uint256 newSupplyValue = totalSupplyAt(block.timestamp); address account; if (isAdding) { newSupplyValue = newSupplyValue.add(value); account = to; } else { newSupplyValue = newSupplyValue.sub(value); account = from; } _createTotalSupplySnapshot(account, newSupplyValue); } } /** * @notice returns true (isHetero) for a mix-match of whitelisted & nonwhitelisted account transfers * returns true (isAdding) if total supply is increasing or false for decreasing * @param from address * @param to address * @return isHetero, isAdding. bool, bool */ function _isWhitelistedHeterogeneousTransfer(address from, address to) internal view returns (bool isHetero, bool isAdding) { bool _isToWhitelisted = isWhitelisted(to); bool _isFromWhitelisted = isWhitelisted(from); if (!_isFromWhitelisted && _isToWhitelisted) { isHetero = true; isAdding = true; // increase whitelisted total supply } else if (_isFromWhitelisted && !_isToWhitelisted) { isHetero = true; } } /** OVERRIDE * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { if (isWhitelisted(account)) { super._createTotalSupplySnapshot(account, amount); } } /** OVERRIDE * @notice only snapshot if account is whitelisted * @param account address * @param amount uint256 */ function _createAccountSnapshot(address account, uint256 amount) internal { if (isWhitelisted(account)) { super._createAccountSnapshot(account, amount); } } function _precheckSnapshot() internal onlyWhitelisted {} } // File: contracts/STO/BaseOptedIn.sol /** * @title Base Opt In * @author Validity Labs AG <info@validitylabs.org> * This allows accounts to "opt out" or "opt in" * Defaults everyone to opted in * Example: opt out from onchain dividend payments */ pragma solidity ^0.5.7; contract BaseOptedIn { // uint256 = timestamp. Default: 0 = opted in. > 0 = opted out mapping(address => uint256) public optedOutAddresses; // whitelisters who've opted to receive offchain dividends /** EVENTS **/ event OptedOut(address indexed account); event OptedIn(address indexed account); modifier onlyOptedBool(bool isIn) { // true for onlyOptedIn, false for onlyOptedOut if (isIn) { require(optedOutAddresses[msg.sender] > 0, "already opted in"); } else { require(optedOutAddresses[msg.sender] == 0, "already opted out"); } _; } /** * @notice accounts who have opted out from onchain dividend payments */ function optOut() public onlyOptedBool(false) { optedOutAddresses[msg.sender] = block.timestamp; emit OptedOut(msg.sender); } /** * @notice accounts who previously opted out, who opt back in */ function optIn() public onlyOptedBool(true) { optedOutAddresses[msg.sender] = 0; emit OptedIn(msg.sender); } /** * @notice returns true if opted in * @param account address * @return optedIn bool */ function isOptedIn(address account) public view returns (bool optedIn) { if (optedOutAddresses[account] == 0) { optedIn = true; } } } // File: contracts/STO/token/OptedInSnapshot.sol /** * @title Opted In Snapshot * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; /** * Opted In Snapshot repurposes the following 2 variables inherited from ERC20Snapshot: * _snapshotBalances: snapshots of opted in accounts * _snapshotTotalSupply: only the total sum of opted in accounts */ contract OptedInSnapshot is ERC20Snapshot, BaseOptedIn { /** OVERRIDE * @notice accounts who previously opted out, who opt back in */ function optIn() public { // protects against TODO: Fill later super._precheckSnapshot(); super.optIn(); address account = msg.sender; uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); _createTotalSupplySnapshot(account, totalSupplyAt(now).add(balance)); } /** OVERRIDE * @notice call parent f(x) & * create new snapshot for account: setting to 0 * create new shapshot for total supply: oldTotalSupply.sub(balance) */ function optOut() public { // protects against TODO: Fill later super._precheckSnapshot(); super.optOut(); address account = msg.sender; _createAccountSnapshot(account, 0); _createTotalSupplySnapshot(account, totalSupplyAt(now).sub(balanceOf(account))); } /** OVERRIDE * @notice Transfer tokens between two accounts while enforcing the update of Snapshots * @param from The address to transfer from * @param to The address to transfer to * @param value The amount to be transferred */ function _transfer(address from, address to, uint256 value) internal { // if available will call the sibiling's inherited function before calling the parent's super._transfer(from, to, value); /** * Possibilities: * Homogeneous Transfers: * 0: opted in to opted in: 0 total supply snapshot * 1: opted out to opted out: 0 total supply snapshot * Heterogeneous Transfers: * 2: opted out to opted in: 1 whitelisted total supply snapshot * 3: opted in to opted out: 1 whitelisted total supply snapshot */ // isOptedHetero tells us to/from is a mix of opted in/out accounts // isAdding tell us whether or not to add or subtract from the opted in total supply value (bool isOptedHetero, bool isAdding) = _isOptedHeterogeneousTransfer(from, to); if (isOptedHetero) { // one account is whitelisted, the other is not uint256 newSupplyValue = totalSupplyAt(block.timestamp); address account; if (isAdding) { newSupplyValue = newSupplyValue.add(value); account = to; } else { newSupplyValue = newSupplyValue.sub(value); account = from; } _createTotalSupplySnapshot(account, newSupplyValue); } } /** * @notice returns true for a mix-match of opted in & opted out transfers. * if true, returns true/false for increasing either optedIn or opetedOut total supply balances * @dev should only be calling if both to and from accounts are whitelisted * @param from address * @param to address * @return isOptedHetero, isOptedInIncrease. bool, bool */ function _isOptedHeterogeneousTransfer(address from, address to) internal view returns (bool isOptedHetero, bool isOptedInIncrease) { bool _isToOptedIn = isOptedIn(to); bool _isFromOptedIn = isOptedIn(from); if (!_isFromOptedIn && _isToOptedIn) { isOptedHetero = true; isOptedInIncrease = true; // increase opted in total supply } else if (_isFromOptedIn && !_isToOptedIn) { isOptedHetero = true; } } /** OVERRIDE * @notice creates a total supply snapshot & emits event * @param amount uint256 * @param account address */ function _createTotalSupplySnapshot(address account, uint256 amount) internal { if (isOptedIn(account)) { super._createTotalSupplySnapshot(account, amount); } } /** OVERRIDE * @notice only snapshot if opted in * @param account address * @param amount uint256 */ function _createAccountSnapshot(address account, uint256 amount) internal { if (isOptedIn(account)) { super._createAccountSnapshot(account, amount); } } } // File: contracts/STO/token/ERC20ForceTransfer.sol /** * @title ERC20 ForceTransfer * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; /** * @dev inherit contract, create external/public function that calls these internal functions * to activate the ability for one or both forceTransfer implementations */ contract ERC20ForceTransfer is Ownable, ERC20 { event ForcedTransfer(address indexed confiscatee, uint256 amount, address indexed receiver); /** * @notice takes all funds from confiscatee and sends them to receiver * @param confiscatee address who's funds are being confiscated * @param receiver address who's receiving the funds */ function forceTransfer(address confiscatee, address receiver) external onlyOwner { uint256 balance = balanceOf(confiscatee); _transfer(confiscatee, receiver, balance); emit ForcedTransfer(confiscatee, balance, receiver); } /** * @notice takes an amount of funds from confiscatee and sends them to receiver * @param confiscatee address who's funds are being confiscated * @param receiver address who's receiving the funds */ function forceTransfer(address confiscatee, address receiver, uint256 amount) external onlyOwner { _transfer(confiscatee, receiver, amount); emit ForcedTransfer(confiscatee, amount, receiver); } } // File: contracts/STO/BaseDocumentRegistry.sol /** * @title Base Document Registry Contract * @author Validity Labs AG <info@validitylabs.org> * inspired by Neufund's iAgreement smart contract */ pragma solidity ^0.5.7; // solhint-disable not-rely-on-time contract BaseDocumentRegistry is Ownable { using SafeMath for uint256; struct HashedDocument { uint256 timestamp; string documentUri; } HashedDocument[] private _documents; event AddedLogDocumented(string documentUri, uint256 documentIndex); /** * @notice adds a document's uri from IPFS to the array * @param documentUri string */ function addDocument(string calldata documentUri) external onlyOwner { require(bytes(documentUri).length > 0, "invalid documentUri"); HashedDocument memory document = HashedDocument({ timestamp: block.timestamp, documentUri: documentUri }); _documents.push(document); emit AddedLogDocumented(documentUri, _documents.length.sub(1)); } /** * @notice fetch the latest document on the array * @return uint256, string, uint256 */ function currentDocument() public view returns (uint256 timestamp, string memory documentUri, uint256 index) { require(_documents.length > 0, "no documents exist"); uint256 last = _documents.length.sub(1); HashedDocument storage document = _documents[last]; return (document.timestamp, document.documentUri, last); } /** * @notice adds a document's uri from IPFS to the array * @param documentIndex uint256 * @return uint256, string, uint256 */ function getDocument(uint256 documentIndex) public view returns (uint256 timestamp, string memory documentUri, uint256 index) { require(documentIndex < _documents.length, "invalid index"); HashedDocument storage document = _documents[documentIndex]; return (document.timestamp, document.documentUri, documentIndex); } /** * @notice return the total amount of documents in the array * @return uint256 */ function documentCount() public view returns (uint256) { return _documents.length; } } // File: contracts/examples/ExampleSecurityToken.sol /** * @title Example Security Token * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; contract ExampleSecurityToken is Utils, Reclaimable, ERC20Detailed, WhitelistedSnapshot, OptedInSnapshot, ERC20Mintable, ERC20Burnable, ERC20Pausable, ERC20ForceTransfer, BaseDocumentRegistry { bool private _isSetup; /** * @notice contructor for the token contract */ constructor(string memory name, string memory symbol, address initialAccount, uint256 initialBalance) public ERC20Detailed(name, symbol, 0) { // pause(); _mint(initialAccount, initialBalance); roleSetup(initialAccount); } /** * @notice setup roles and contract addresses for the new token * @param board Address of the owner who is also a manager */ function roleSetup(address board) internal onlyOwner onlyOnce(_isSetup) { addMinter(board); addPauser(board); _addWhitelistAdmin(board); } /** OVERRIDE - onlyOwner role (the board) can call * @notice Burn tokens of one account * @param account The address whose tokens will be burnt * @param value The amount of tokens to be burnt */ function _burn(address account, uint256 value) internal onlyOwner { super._burn(account, value); } } // File: contracts/STO/dividends/Dividends.sol /** * @title Dividend contract for STO * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity ^0.5.7; contract Dividends is Utils, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; address public _wallet; // set at deploy time struct Dividend { uint256 recordDate; // timestamp of the record date uint256 claimPeriod; // claim period, in seconds, of the claiming period address payoutToken; // payout token, which could be different each time. uint256 payoutAmount; // the total amount of tokens deposit uint256 claimedAmount; // the total amount of tokens being claimed uint256 totalSupply; // the total supply of sto token when deposit was made bool reclaimed; // If the unclaimed deposit was reclaimed by the team mapping(address => bool) claimed; // If investors have claimed their dividends. } address public _token; Dividend[] public dividends; // Record the balance of each ERC20 token deposited to this contract as dividends. mapping(address => uint256) public totalBalance; // EVENTS event DepositedDividend(uint256 indexed dividendIndex, address indexed payoutToken, uint256 payoutAmount, uint256 recordDate, uint256 claimPeriod); event ReclaimedDividend(uint256 indexed dividendIndex, address indexed claimer, uint256 claimedAmount); event RecycledDividend(uint256 indexed dividendIndex, uint256 timestamp, uint256 recycledAmount); /** * @notice Check if the index is valid */ modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length, "Such dividend does not exist"); _; } /** * @notice initialize the Dividend contract with the STO Token contract and the new owner * @param stoToken The token address, of which the holders could claim dividends. * @param wallet the address of the wallet to receive the reclaimed funds */ /* solhint-disable */ constructor(address stoToken, address wallet) public onlyValidAddress(stoToken) onlyValidAddress(wallet) { _token = stoToken; _wallet = wallet; transferOwnership(wallet); } /* solhint-enable */ /** * @notice deposit payoutDividend tokens (ERC20) into this contract * @param payoutToken ERC20 address of the token used for payout the current dividend * @param amount uint256 total amount of the ERC20 tokens deposited to payout to all * token holders as of previous block from when this function is included * @dev The owner should first call approve(STODividendsContractAddress, amount) * in the payoutToken contract */ function depositDividend(address payoutToken, uint256 recordDate, uint256 claimPeriod, uint256 amount) public onlyOwner onlyValidAddress(payoutToken) { require(amount > 0, "invalid deposit amount"); require(recordDate > 0, "invalid recordDate"); require(claimPeriod > 0, "invalid claimPeriod"); IERC20(payoutToken).safeTransferFrom(msg.sender, address(this), amount); // transfer ERC20 to this contract totalBalance[payoutToken] = totalBalance[payoutToken].add(amount); // update global balance of ERC20 token dividends.push( Dividend( recordDate, claimPeriod, payoutToken, amount, 0, ERC20Snapshot(_token).totalSupplyAt(block.timestamp), //eligible supply false ) ); emit DepositedDividend((dividends.length).sub(1), payoutToken, amount, block.timestamp, claimPeriod); } /** TODO: check for "recycle" or "recycled" - replace with reclaimed * @notice Token holder claim their dividends * @param dividendIndex The index of the deposit dividend to be claimed. */ function claimDividend(uint256 dividendIndex) public validDividendIndex(dividendIndex) { Dividend storage dividend = dividends[dividendIndex]; require(dividend.claimed[msg.sender] == false, "Dividend already claimed"); require(dividend.reclaimed == false, "Dividend already reclaimed"); require((dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp, "No longer claimable"); _claimDividend(dividendIndex, msg.sender); } /** * @notice Claim dividends from a startingIndex to all possible dividends * @param startingIndex The index from which the loop of claiming dividend starts * @dev To claim all dividends from the beginning, set this value to 0. * This parameter may help reducing the risk of running out-of-gas due to many loops */ function claimAllDividends(uint256 startingIndex) public validDividendIndex(startingIndex) { for (uint256 i = startingIndex; i < dividends.length; i++) { Dividend storage dividend = dividends[i]; if (dividend.claimed[msg.sender] == false && (dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp && dividend.reclaimed == false) { _claimDividend(i, msg.sender); } } } /** * @notice recycle the dividend. Transfer tokens back to the _wallet * @param dividendIndex the storage index of the dividend in the pushed array. */ function reclaimDividend(uint256 dividendIndex) public onlyOwner validDividendIndex(dividendIndex) { Dividend storage dividend = dividends[dividendIndex]; require(dividend.reclaimed == false, "Dividend already reclaimed"); require((dividend.recordDate).add(dividend.claimPeriod) < block.timestamp, "Still claimable"); dividend.reclaimed = true; uint256 recycledAmount = (dividend.payoutAmount).sub(dividend.claimedAmount); totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(recycledAmount); IERC20(dividend.payoutToken).safeTransfer(_wallet, recycledAmount); emit RecycledDividend(dividendIndex, block.timestamp, recycledAmount); } /** * @notice get dividend info at index * @param dividendIndex the storage index of the dividend in the pushed array. * @return recordDate (uint256) of the dividend * @return claimPeriod (uint256) of the dividend * @return payoutToken (address) of the dividend * @return payoutAmount (uint256) of the dividend * @return claimedAmount (uint256) of the dividend * @return the total supply (uint256) of the dividend * @return Whether this dividend was reclaimed (bool) of the dividend */ function getDividend(uint256 dividendIndex) public view validDividendIndex(dividendIndex) returns (uint256, uint256, address, uint256, uint256, uint256, bool) { Dividend memory result = dividends[dividendIndex]; return ( result.recordDate, result.claimPeriod, address(result.payoutToken), result.payoutAmount, result.claimedAmount, result.totalSupply, result.reclaimed); } /** * @notice Internal function that claim the dividend * @param dividendIndex the index of the dividend to be claimed * @param account address of the account to receive dividend */ function _claimDividend(uint256 dividendIndex, address account) internal { Dividend storage dividend = dividends[dividendIndex]; uint256 claimAmount = _calcClaim(dividendIndex, account); dividend.claimed[account] = true; dividend.claimedAmount = (dividend.claimedAmount).add(claimAmount); totalBalance[dividend.payoutToken] = totalBalance[dividend.payoutToken].sub(claimAmount); IERC20(dividend.payoutToken).safeTransfer(account, claimAmount); emit ReclaimedDividend(dividendIndex, account, claimAmount); } /** * @notice calculate dividend claim amount */ function _calcClaim(uint256 dividendIndex, address account) internal view returns (uint256) { Dividend memory dividend = dividends[dividendIndex]; uint256 balance = ERC20Snapshot(_token).balanceOfAt(account, dividend.recordDate); return balance.mul(dividend.payoutAmount).div(dividend.totalSupply); } } // File: contracts/examples/ExampleTokenFactory.sol /** * @title Example Token Factory Contract * @author Validity Labs AG <info@validitylabs.org> */ pragma solidity 0.5.7; /* solhint-disable max-line-length */ /* solhint-disable separate-by-one-line-in-contract */ contract ExampleTokenFactory is Managed { mapping(address => address) public tokenToDividend; /*** EVENTS ***/ event DeployedToken(address indexed contractAddress, string name, string symbol, address indexed clientOwner); event DeployedDividend(address indexed contractAddress); /*** FUNCTIONS ***/ function newToken(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner { address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount); } function newTokenAndDividend(string calldata _name, string calldata _symbol, address _clientOwner, uint256 _initialAmount) external onlyOwner { address tokenAddress = _deployToken(_name, _symbol, _clientOwner, _initialAmount); address dividendAddress = _deployDividend(tokenAddress, _clientOwner); tokenToDividend[tokenAddress] = dividendAddress; } /** MANGER FUNCTIONS **/ /** * @notice Prospectus and Quarterly Reports * @dev string null check is done at the token level - see ERC20DocumentRegistry * @param _est address of the targeted EST * @param _documentUri string IPFS URI to the document */ function addDocument(address _est, string calldata _documentUri) external onlyValidAddress(_est) onlyManager { ExampleSecurityToken(_est).addDocument(_documentUri); } /** * @notice pause or unpause individual EST * @param _est address of the targeted EST */ function togglePauseEST(address _est) public onlyValidAddress(_est) onlyManager { ExampleSecurityToken est = ExampleSecurityToken(_est); bool result = est.paused(); result ? est.unpause() : est.pause(); } /** * @notice force the transfer of tokens from _confiscatee to _receiver * @param _est address of the targeted EST * @param _confiscatee address to confiscate tokens from * @param _receiver address to receive the balance of tokens * @param _amount uint256 amount to take away from _confiscatee */ function forceTransferEST(address _est, address _confiscatee, address _receiver, uint256 _amount) public onlyValidAddress(_est) onlyValidAddress(_confiscatee) onlyValidAddress(_receiver) onlyManager { require(_amount > 0, "invalid amount"); ExampleSecurityToken est = ExampleSecurityToken(_est); est.forceTransfer(_confiscatee, _receiver, _amount); } function _deployToken(string memory _name, string memory _symbol, address _clientOwner, uint256 _initialAmount) internal returns (address) { require(bytes(_name).length > 0, "name cannot be blank"); require(bytes(_symbol).length > 0, "symbol cannot be blank"); ExampleSecurityToken tokenContract = new ExampleSecurityToken(_name, _symbol, _clientOwner, _initialAmount); emit DeployedToken(address(tokenContract), _name, _symbol, _clientOwner); return address(tokenContract); } function _deployDividend(address tokenAddress, address wallet) internal returns (address) { Dividends dividendContract = new Dividends(tokenAddress, wallet); emit DeployedDividend(address(dividendContract)); return address(dividendContract); } }
Claim dividends from a startingIndex to all possible dividends startingIndex The index from which the loop of claiming dividend starts To claim all dividends from the beginning, set this value to 0. This parameter may help reducing the risk of running out-of-gas due to many loops/
function claimAllDividends(uint256 startingIndex) public validDividendIndex(startingIndex) { for (uint256 i = startingIndex; i < dividends.length; i++) { Dividend storage dividend = dividends[i]; if (dividend.claimed[msg.sender] == false && (dividend.recordDate).add(dividend.claimPeriod) >= block.timestamp && dividend.reclaimed == false) { _claimDividend(i, msg.sender); } } }
5,444,885
/** *Submitted for verification at Etherscan.io on 2022-03-19 */ // File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/access/AccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/access/IAccessControlEnumerable.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File: @openzeppelin/contracts/access/AccessControlEnumerable.sol // OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // File: ESombra_erc20_final.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev 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); } } interface SwapAndLiquifier { function swapAndLiquify(uint256 contractTokenBalance) external; } contract Sombra is Context, IERC20Metadata, Ownable, AccessControlEnumerable { string private constant NAME = "SOMBRA"; string private constant SYMBOL = "SMBR"; uint8 private constant DECIMALS = 9; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; uint256 private constant MAX_INT = ~uint256(0); uint256 private TOTAL_SUPPLY = 0; uint256 private MAX_SUPPLY = 100000000 * 10**DECIMALS; uint256 private REFLECTION_TOTAL = (MAX_INT - (MAX_INT % MAX_SUPPLY)); uint256 private _tFeeTotal; // _tSupply and _rSupply keep track of the reflection-tokens supply. // Essentially, they are the total supply minus balances of excluded addresses. uint256 private _tSupply = 0; uint256 private _rSupply = 0; uint256 public _taxFee = 3; uint256 public _liquidityFee = 3; event TaxFeeUpdated(uint256 oldTaxFee, uint256 newTaxFee); event LiquidityFeeUpdated(uint256 oldLiqFee, uint256 newLiqFee); // IUniswapV2Router02 public uniswapV2Router; // IUniswapV2Pair public uniswapV2Pair; // address private WETH; event UniswapRouterUpdated(address newRouter); mapping (address => bool) public marketPair; event MarketPairUpdated(address pair, bool isMarketPair); bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 private numTokensSellToAddToLiquidity = 100000 * 10**DECIMALS; // current swapAndLiquify contract address address swap_and_liquify_contract; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event ExcludedFromReward(address account); event IncludedInReward(address account); event ExcludedFromFee(address account); event IncludedInFee(address account); // burn permissions bool burn_approval_required = false; mapping (address => bool) public give_right_to_burn; // events and variables for crosschain event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount); event LogSwapout(address indexed account, address indexed bindaddr, uint amount); // flag to enable/disable swapout vs vault.burn so multiple events are triggered // Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens bool private _vaultOnly = false; address public vault; function setVaultOnly(bool enabled) external onlyOperator() { _vaultOnly = enabled; } modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } // roles for access control // bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE"); constructor() { // set up roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); _setupRole(VAULT_ROLE, _msgSender()); //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; uint256 chainId; assembly {chainId := chainid()} DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes("SOMBRA")), keccak256(bytes("1")), chainId, address(this))); } modifier onlyOperator() { require( hasRole(OPERATOR_ROLE, _msgSender()), 'must have operator role to use this function' ); _; } function name() public pure override returns (string memory) { return NAME; } function symbol() public pure override returns (string memory) { return SYMBOL; } function decimals() public pure override returns (uint8) { return DECIMALS; } function totalSupply() public view override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } function taxCollected() external view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) external { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,,) = _getValues(tAmount, false); _rOwned[sender] = _rOwned[sender] - rAmount; _rSupply = _rSupply - rAmount; _tFeeTotal = _tFeeTotal + tAmount; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= MAX_SUPPLY, "Amount must be less than supply"); (,uint256 rTransferAmount,,,,,) = _getValues(tAmount, deductTransferFee); return rTransferAmount; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rSupply, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function excludeFromReward(address account) external onlyOperator() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); uint256 rBalance = _rOwned[account]; if(rBalance > 0) { uint256 rTokens = tokenFromReflection(rBalance); _tOwned[account] = rTokens; _rSupply -= rBalance; _tSupply -= rTokens; } _isExcluded[account] = true; emit ExcludedFromReward(account); } function includeInReward(address account) external onlyOperator() { require(_isExcluded[account], "Account is already excluded"); uint256 tOwned = _tOwned[account]; uint256 rAmount = reflectionFromToken(tOwned, false); _tSupply += tOwned; _rSupply += rAmount; _rOwned[account] = rAmount; _tOwned[account] = 0; _isExcluded[account] = false; emit IncludedInReward(account); } function burn(address from, uint256 amount) public returns(bool){ // require this is called to burn your own tokens or an address that has the BURNER_ROLE require(from == _msgSender() || hasRole(BURNER_ROLE, _msgSender()) || hasRole(OPERATOR_ROLE, _msgSender()) || _msgSender() == vault ,"DOES NOT HAVE RIGHT TO BURN"); if (from != _msgSender()){ uint256 currentAllowance = _allowances[from][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(from, _msgSender(), currentAllowance - amount); } } require(from != address(0), "do not burn from the zero address"); // determine if the address from which tokens are being burned is excluded from reflective rewards bool isExcludedSender = _isExcluded[from]; if (isExcludedSender){ //check that in fact the _tOwned of the burner is greater than the ammount requested to be burned require(_tOwned[from] >= amount, "in burn: not enough balance owned by from address"); _tOwned[from] -= amount; // emit the transfer event to indicate the burning to the "zero" address emit Transfer(from,address(0), amount); TOTAL_SUPPLY -= amount; // return true successful burning return true; } // if control gets to here then the burner address is included in the reward // we will calculate the appropriate ammount of reflection to remove uint256 rAmount = reflectionFromToken(amount, false); //check that in fact the _rOwned of the burner is greater than the calculated ammount require(_rOwned[from] >= rAmount, "in burn: not enough balance owned by from address"); unchecked { _rOwned[from] -= rAmount; } _rSupply -= rAmount; _tSupply -= amount; emit Transfer(from, address(0), amount); TOTAL_SUPPLY -= amount; // return true successful burning return true; } function mint(address to, uint256 amount) public returns(bool) { // require this is called by an address that has the MINTER_ROLE require(hasRole(MINTER_ROLE, _msgSender()) || hasRole(OPERATOR_ROLE, _msgSender()) || _msgSender() == vault ,"DOES NOT HAVE RIGHT TO MINT"); require((TOTAL_SUPPLY + amount) <= MAX_SUPPLY, "Minting over MAX_SUPPLY is not permitted"); require(to != address(0), "do not mint to the zero address"); // determine if recipient is excluded from reflective rewards bool isExcludedRecipient = _isExcluded[to]; // if the reciever is excluded from the reward then simply increase the _tOwned amount by // the desired amount of tokens if (isExcludedRecipient){ _tOwned[to] += amount; // emit the transfer event to indicate the minting from the "zero" address emit Transfer(address(0), to, amount); // now increase the total supply of the token by the ammount TOTAL_SUPPLY += amount; // return true successful minting return true; } // if control gets to here then the recipient of the mint is included in the reward // we will calculate the appropriate ammount of reflection to give them uint256 rAmount = reflectionFromToken(amount, false); // now based on the amount of tokens minted and the reflection amount change the _tSupply // and the _rSupply respectively _tSupply += amount; _rSupply += rAmount; // increast the _rOwned of the recipient _rOwned[to] += rAmount; // emit the transfer event to indicate the minting from the "zero" address emit Transfer(address(0), to, amount); // now increase the total supply of the token by the ammount TOTAL_SUPPLY += amount; // return true successful minting return true; } /// the following Swapin and Swapout functions are for the benifit of anyswap bridge capabilities // function Swapin(bytes32 txhash, address account, uint256 amount) public returns (bool) { // require this is called by an address that has the MINTER_ROLE require(hasRole(MINTER_ROLE, _msgSender()) || hasRole(OPERATOR_ROLE, _msgSender()) || _msgSender() == vault ,"DOES NOT HAVE RIGHT TO MINT"); mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public returns (bool) { require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth"); require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)"); burn(_msgSender(), amount); emit LogSwapout(_msgSender(), bindaddr, amount); return true; } function changeVault(address newVault) external returns (bool) { // require vault has access now // require(hasRole(OPERATOR_ROLE, _msgSender()) || _msgSender() == vault ,"DOES NOT HAVE RIGHT TO CHANGE VAULT"); vault = newVault; // give vault minting burning swapin and swapout rights // return true; } // for compatibility for older versions function changeMPCOwner(address newVault) external returns (bool) { // require vault has access now // require(hasRole(OPERATOR_ROLE, _msgSender()) || _msgSender() == vault ,"DOES NOT HAVE RIGHT TO CHANGE VAULT"); vault = newVault; // give vault minting burning swapin and swapout rights // return true; } ///////// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public immutable DOMAIN_SEPARATOR; /// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}. /// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times. mapping (address => uint256) public nonces; /// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval. /// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); _approve(target, spender, value); emit Approval(target, spender, value); } function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) { bytes32 hash = prefixed(hashStruct); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal view returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", DOMAIN_SEPARATOR, hash)); } ///// /// function excludeFromFee(address account) external onlyOperator { _isExcludedFromFee[account] = true; emit ExcludedFromFee(account); } function includeInFee(address account) external onlyOperator { _isExcludedFromFee[account] = false; emit IncludedInFee(account); } function setTaxFee(uint256 taxFee) external onlyOperator { require(taxFee + _liquidityFee <= 6, "Fees cannot exceed 6%"); uint256 currentTaxFee = _taxFee; require(taxFee != currentTaxFee, "Tax fee cannot be the same"); _taxFee = taxFee; emit TaxFeeUpdated(currentTaxFee, taxFee); } function setLiquidityFee(uint256 liquidityFee) external onlyOperator { require(_taxFee + liquidityFee <= 6, "Fees cannot exceed 6%"); uint256 currentLiqFee = _liquidityFee; require(liquidityFee != currentLiqFee, "Liquidity fee cannot be the same"); _liquidityFee = liquidityFee; emit LiquidityFeeUpdated(currentLiqFee, liquidityFee); } function setMinTokensToSwapAndLiquify(uint256 minTokens) external onlyOperator { numTokensSellToAddToLiquidity = minTokens * 10**DECIMALS; emit MinTokensBeforeSwapUpdated(numTokensSellToAddToLiquidity); } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOperator { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // function to change the swapAndLiquify contract // function setSwapAndLiquifyContractAddress(address newAddress) public onlyOperator { address oldAddress = swap_and_liquify_contract; swap_and_liquify_contract = newAddress; // Approve the new router to spend contract's tokens. _approve(address(this), newAddress, MAX_INT); // Reset approval on old router. and prevent failure if address is not set/ set to address(0) if (oldAddress != address(0)){ _approve(address(this), oldAddress, 0); } } function updateMarketPair(address pair, bool isPair) external onlyOperator { _updateMarketPair(pair, isPair); } function _updateMarketPair(address pair, bool isPair) private { require(marketPair[pair] != isPair, "Pair already set"); marketPair[pair] = isPair; emit MarketPairUpdated(pair, isPair); } // burn permissions setters function setBurningApprovalRequired(bool allow) external onlyOperator(){ burn_approval_required = allow; } function setAllowBurning(bool allow) external { give_right_to_burn[_msgSender()] = allow; } // this is to recover erc20 tokens in this contract // or to manually add liquidity if not using swapandliquify function transferToken(address token, uint amount, address receiver) onlyOperator() public{ IERC20 erc20 = IERC20(token); erc20.transfer(receiver, amount); } // Use struct for RValues to prevent stack too deep error. struct _RValues { uint256 rAmount; uint256 rTransferAmount; uint256 rFee; uint256 rLiquidity; } // Retrieves rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity for provided tAmount. function _getValues(uint256 tAmount, bool takeFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { if(!takeFee) { uint256 rTokens = tAmount * _getRate(); return (rTokens, rTokens, 0, tAmount, 0, 0, 0); } (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); _RValues memory r = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (r.rAmount, r.rTransferAmount, r.rFee, tTransferAmount, tFee, tLiquidity, r.rLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount - tFee - tLiquidity; return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (_RValues memory) { uint256 rAmount = tAmount * currentRate; uint256 rFee = tFee * currentRate; uint256 rLiquidity = tLiquidity * currentRate; uint256 rTransferAmount = rAmount - rFee - rLiquidity; return _RValues( rAmount, rTransferAmount, rFee, rLiquidity ); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } function _getCurrentSupply() private view returns(uint256, uint256) { // _tSupply is 0 when every token is held by excluded wallet. uint256 tSupply = _tSupply; if(tSupply == 0) return (REFLECTION_TOTAL, MAX_SUPPLY); return (_rSupply, tSupply); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rSupply = _rSupply - rFee; _tFeeTotal = _tFeeTotal + tFee; } function _takeLiquidity(address sender, uint256 rLiquidity, uint256 tLiquidity) private { if(_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)] + tLiquidity; _rSupply -= rLiquidity; _tSupply -= tLiquidity; } else { _rOwned[address(this)] = _rOwned[address(this)] + rLiquidity; } emit Transfer(sender, address(this), tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount * _taxFee / (10 ** 2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount * _liquidityFee / (10 ** 2); } function isExcludedFromFee(address account) external view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); bool isRecipientMarketPair = marketPair[to]; bool isSenderMarketPair = marketPair[from]; // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); uint256 numTokens = numTokensSellToAddToLiquidity; bool overMinTokenBalance = contractTokenBalance >= numTokens; if ( overMinTokenBalance && !inSwapAndLiquify && isRecipientMarketPair && // Only swap & liquify on sells. !isSenderMarketPair && swapAndLiquifyEnabled ) { // Try to swap and liquify. inSwapAndLiquify = true; // swapper is approved and does a transferfrom then executes the appropriate liquidity logic // factored out so that different liquidity interfaces can be supported SwapAndLiquifier swapper = SwapAndLiquifier(swap_and_liquify_contract); try swapper.swapAndLiquify(contractTokenBalance) {} catch { } inSwapAndLiquify = false; } // Only deduct fee if the transaction is to/from the market pair. bool takeFee = (isRecipientMarketPair || isSenderMarketPair); //if any account belongs to _isExcludedFromFee account then remove the fee if(takeFee && (_isExcludedFromFee[from] || _isExcludedFromFee[to])) { takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { bool isExcludedSender = _isExcluded[sender]; bool isExcludedRecipient = _isExcluded[recipient]; if (isExcludedSender && !isExcludedRecipient) { _transferFromExcluded(sender, recipient, amount, takeFee); } else if (!isExcludedSender && isExcludedRecipient) { _transferToExcluded(sender, recipient, amount, takeFee); } else if (!isExcludedSender && !isExcludedRecipient) { _transferStandard(sender, recipient, amount, takeFee); } else if (isExcludedSender && isExcludedRecipient) { _transferBothExcluded(sender, recipient, amount, takeFee); } } function _transferStandard(address sender, address recipient, uint256 tAmount, bool takeFee) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee); require(_rOwned[sender] >= rAmount, "Insufficient Balance"); unchecked { _rOwned[sender] -= rAmount; } _rOwned[recipient] += rTransferAmount; // Do not have to change the supply when transfering from/to standard accounts. if(tLiquidity != 0) { _takeLiquidity(sender, rLiquidity, tLiquidity); } if(tFee != 0) { _reflectFee(rFee, tFee); } emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount, bool takeFee) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee); require(_tOwned[sender] >= tAmount, "Insufficient Balance"); unchecked { _tOwned[sender] -= tAmount; } _tOwned[recipient] += tTransferAmount; // Increase the supply by amount spent on taxes. As that amount is no longer held by an excluded wallet. _rSupply += (rAmount - rTransferAmount); _tSupply += (tAmount - tTransferAmount); if(tLiquidity != 0) { _takeLiquidity(sender, rLiquidity, tLiquidity); } if(tFee != 0) { _reflectFee(rFee, tFee); } emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount, bool takeFee) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee); require(_rOwned[sender] >= rAmount, "Insufficient Balance"); unchecked { _rOwned[sender] -= rAmount; } _tOwned[recipient] += tTransferAmount; // Decrease the supply by the amount of tokens the user received, as that is now held by an excluded wallet. _rSupply -= rTransferAmount; _tSupply -= tTransferAmount; if(tLiquidity != 0) { _takeLiquidity(sender, rLiquidity, tLiquidity); } if(tFee != 0) { _reflectFee(rFee, tFee); } emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount, bool takeFee) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee); require(_tOwned[sender] >= tAmount, "Insufficient Balance"); unchecked { _tOwned[sender] -= tAmount; } _rOwned[recipient] += rTransferAmount; // Increase the supply by the amount of tokens the user sent, as that is no longer held by an excluded wallet. _rSupply += rAmount; _tSupply += tAmount; if(tLiquidity != 0) { _takeLiquidity(sender, rLiquidity, tLiquidity); } if(tFee != 0) { _reflectFee(rFee, tFee); } emit Transfer(sender, recipient, tTransferAmount); } }
Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval. Emits {Approval} event. Requirements: - `deadline` must be timestamp in future. - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. - the signature must use `owner` account's current nonce (see {nonces}). - the signer cannot be zero address and must be `owner` account. For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612specification[relevant EIP section]. AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol.
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); _approve(target, spender, value); emit Approval(target, spender, value); }
8,019,224
./partial_match/3/0xB0d1334d04E02b827304861DF402fabf96056421/sources/Governance.sol
propose to update the whitelist. proposer needs to commit minimum deposit amount./
function proposeUpdateWhitelist(address tokenAddress, address oracleAddress) external { require(oracleAddress != address(0), "cannot propose zero address for oracleAddress"); bytes32 proposeId = keccak256(abi.encode(tokenAddress, oracleAddress)); uint256 prevoteDeadline = _getBlockTimestampSec() + _preVoteLength; uint256 mainvoteDeadline = _getBlockTimestampSec() + _mainVoteLength; uint256 appliedMinimumVote = _taxTokenContract.totalSupply().mul(_minimumVoteE4).div(10**4); uint256 appliedMinCommit = _taxTokenContract.totalSupply().mul(_minimumCommitE4).div(10**4); require( proposeStatus[proposeId].mainvoteDeadline == 0 || proposeStatus[proposeId].mainvoteDeadline + _expirationLength <= _getBlockTimestampSec(), "the proposal should not conflict with the ongoing proposal" ); proposeStatus[proposeId] = ProposeStatus({ prevoteDeadline: prevoteDeadline, mainvoteDeadline: mainvoteDeadline, appliedMinimumVote: appliedMinimumVote, currentApprovalVoteSum: appliedMinCommit, currentDenialVoteSum: 0, lockin: false, applied: false }); proposeList[proposeId] = WhitelistParameters({ tokenAddress: tokenAddress, oracleAddress: oracleAddress }); bytes32 account = keccak256(abi.encode(proposeId, msg.sender)); proposeApproval[account] = proposeApproval[account].add(appliedMinCommit); _taxTokenContract.transferFrom(msg.sender, address(this), appliedMinCommit); emit LogProposeUpdateWhiteList( proposeId, tokenAddress, oracleAddress, prevoteDeadline, mainvoteDeadline ); emit LogDeposit(proposeId, msg.sender, true, appliedMinCommit); }
5,321,158
pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } pragma solidity ^0.6.0; import "../interfaces/GasTokenInterface.sol"; contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } pragma solidity ^0.6.0; abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } pragma solidity ^0.6.0; abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsStable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } pragma solidity ^0.6.0; /** @title ILendingPoolAddressesProvider interface @notice provides the interface to fetch the LendingPoolCore address */ abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } pragma solidity ^0.6.0; import "../interfaces/ERC20.sol"; import "./Address.sol"; import "./SafeMath.sol"; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } pragma solidity ^0.6.0; interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } pragma solidity ^0.6.0; library Address { 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); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../interfaces/DSProxyInterface.sol"; import "./SafeERC20.sol"; /// @title Pulls a specified amount of tokens from the EOA owner account to the proxy contract PullTokensProxy { using SafeERC20 for ERC20; /// @notice Pulls a token from the proxyOwner -> proxy /// @dev Proxy owner must first give approve to the proxy address /// @param _tokenAddr Address of the ERC20 token /// @param _amount Amount of tokens which will be transfered to the proxy function pullTokens(address _tokenAddr, uint _amount) public { address proxyOwner = DSProxyInterface(address(this)).owner(); ERC20(_tokenAddr).safeTransferFrom(proxyOwner, address(this), _amount); } } pragma solidity ^0.6.0; abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } pragma solidity ^0.6.0; import "../auth/Auth.sol"; import "../interfaces/DSProxyInterface.sol"; // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } pragma solidity ^0.6.0; import "./AdminAuth.sol"; contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/ILendingPool.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/ILoanShifter.sol"; import "../interfaces/DSProxyInterface.sol"; import "../interfaces/Vat.sol"; import "../interfaces/Manager.sol"; import "../interfaces/IMCDSubscriptions.sol"; import "../interfaces/ICompoundSubscriptions.sol"; import "../auth/AdminAuth.sol"; import "../auth/ProxyPermission.sol"; import "../exchangeV3/DFSExchangeData.sol"; import "./ShifterRegistry.sol"; import "../utils/GasBurner.sol"; import "../loggers/DefisaverLogger.sol"; /// @title LoanShifterTaker Entry point for using the shifting operation contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } // encode data bytes memory paramsData = abi.encode(_loanShift, _exchangeData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return getUnderlyingAddr(_address); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function logEvent( DFSExchangeData.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } pragma solidity ^0.6.0; abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } pragma solidity ^0.6.0; abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } pragma solidity ^0.6.0; abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } pragma solidity ^0.6.0; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } pragma solidity ^0.6.0; abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } pragma solidity ^0.6.0; import "../DS/DSGuard.sol"; import "../DS/DSAuth.sol"; contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; // service fee divider address user; // user to check special fee address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } pragma solidity ^0.6.0; contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } pragma solidity ^0.6.0; abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } pragma solidity ^0.6.0; import "./DSAuthority.sol"; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } pragma solidity ^0.6.0; abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; contract MCDCreateTaker is GasBurner { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x409F216aa8034a12135ab6b74Bf6444335004BBd; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable burnGas(20) { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } bytes memory packedData = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_createData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../loggers/DefisaverLogger.sol"; import "../../utils/Discount.sol"; import "../../interfaces/Spotter.sol"; import "../../interfaces/Jug.sol"; import "../../interfaces/DaiJoin.sol"; import "../../interfaces/Join.sol"; import "./MCDSaverProxyHelper.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; /// @title Implements Boost and Repay for MCD CDPs contract MCDSaverProxy is DFSExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); drawCollateral(managerAddr, _cdpId, _joinAddr, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint daiAmount) = _sell(_exchangeData); daiAmount -= takeFee(_gasCost, daiAmount); paybackDebt(managerAddr, _cdpId, ilk, daiAmount, user); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, user, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable { address managerAddr = getManagerAddr(_managerType); address user = getOwner(Manager(managerAddr), _cdpId); bytes32 ilk = Manager(managerAddr).ilks(_cdpId); uint daiDrawn = drawDai(managerAddr, _cdpId, ilk, _exchangeData.srcAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exchangeData.srcAmount = daiDrawn - takeFee(_gasCost, daiDrawn); (, uint swapedColl) = _sell(_exchangeData); addCollateral(managerAddr, _cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, user, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(Manager(_managerAddr).urns(_cdpId)); uint maxAmount = getMaxDebt(_managerAddr, _cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } Manager(_managerAddr).frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); Manager(_managerAddr).move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( Manager(_managerAddr).ilks(_cdpId), Manager(_managerAddr).urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @param _managerAddr Address of the CDP Manager /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } Manager(_managerAddr).frob(_cdpId, -toPositiveInt(frobAmount), 0); Manager(_managerAddr).flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @param _managerAddr Address of the CDP Manager /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = Manager(_managerAddr).urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Gets the maximum amount of collateral available to draw /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(address _managerAddr, uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(address _managerAddr, uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } function takeFee(uint256 _gasCost, uint _amount) internal returns(uint) { if (_gasCost > 0) { uint ethDaiPrice = getPrice(ETH_ILK); uint feeAmount = rmul(_gasCost, ethDaiPrice); if (feeAmount > _amount / 5) { feeAmount = _amount / 5; } address walletAddr = _feeRecipient.getFeeAddr(); ERC20(DAI_ADDRESS).transfer(walletAddr, feeAmount); return feeAmount; } return 0; } } pragma solidity ^0.6.0; contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } pragma solidity ^0.6.0; import "./PipInterface.sol"; abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } pragma solidity ^0.6.0; abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } pragma solidity ^0.6.0; import "./Vat.sol"; import "./Gem.sol"; abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } pragma solidity ^0.6.0; import "./Gem.sol"; abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } pragma solidity ^0.6.0; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../interfaces/Vat.sol"; /// @title Helper methods for MCDSaverProxy contract MCDSaverProxyHelper is DSMath { enum ManagerType { MCD, BPROTOCOL } /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } /// @notice Based on the manager type returns the address /// @param _managerType Type of vault manager to use function getManagerAddr(ManagerType _managerType) public pure returns (address) { if (_managerType == ManagerType.MCD) { return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; } else if (_managerType == ManagerType.BPROTOCOL) { return 0x3f30c2381CD8B917Dd96EB2f1A4F96D91324BBed; } } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/ZrxAllowlist.sol"; import "./DFSExchangeData.sol"; import "./DFSExchangeHelper.sol"; import "../exchange/SaverExchangeRegistry.sol"; import "../interfaces/OffchainWrapperInterface.sol"; contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_NOT_ZEROX_EXCHANGE = "Zerox exchange invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(EXCHANGE_WETH_ADDRESS).deposit{value: exData.srcAmount}(); } if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } // if anything is left in weth, pull it to user as eth if (getBalance(EXCHANGE_WETH_ADDRESS) > 0) { TokenInterface(EXCHANGE_WETH_ADDRESS).withdraw( TokenInterface(EXCHANGE_WETH_ADDRESS).balanceOf(address(this)) ); } if (exData.destAddr == EXCHANGE_WETH_ADDRESS) { require(getBalance(KYBER_ETH_ADDRESS) >= exData.destAmount, ERR_SLIPPAGE_HIT); } else { require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (!ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { return (false, 0); } if (!SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.offchainData.wrapper)) { return (false, 0); } // send src amount ERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount); return OffchainWrapperInterface(_exData.offchainData.wrapper).takeOrder{value: _exData.offchainData.protocolFee}(_exData, _type); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; abstract contract PipInterface { function read() public virtual returns (bytes32); } pragma solidity ^0.6.0; abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } pragma solidity ^0.6.0; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } pragma solidity ^0.6.0; import "./DSAuth.sol"; import "./DSNote.sol"; abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } pragma solidity ^0.6.0; contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } pragma solidity ^0.6.0; abstract contract TokenInterface { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } pragma solidity ^0.6.0; interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; contract DFSExchangeHelper { string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant EXCHANGE_WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } address walletAddr = _feeRecipient.getFeeAddr(); if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _src; } } pragma solidity ^0.6.0; import "../auth/AdminAuth.sol"; contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchangeV3/DFSExchangeData.sol"; abstract contract OffchainWrapperInterface is DFSExchangeData { function takeOrder( ExchangeData memory _exData, ActionType _type ) virtual public payable returns (bool success, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract IFeeRecipient { function getFeeAddr() public view virtual returns (address); function changeWalletAddr(address _newWallet) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../saver/MCDSaverProxy.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x9222c4f253bD0bdb387Fc97D44e5A6b90cDF4389; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxDebt = getMaxDebt(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr, ManagerType _managerType ) public payable burnGas(25) { address managerAddr = getManagerAddr(_managerType); uint256 maxColl = getMaxCollateral(managerAddr, _cdpId, Manager(managerAddr).ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr, _managerType); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true, uint8(_managerType)); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); Manager(managerAddr).cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/ITokenInterface.sol"; import "../../DS/DSAuth.sol"; contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ProtocolInterface.sol"; import "../interfaces/ERC20.sol"; import "../interfaces/ITokenInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "./dydx/ISoloMargin.sol"; import "./SavingsLogger.sol"; import "./dsr/DSRSavingsProtocol.sol"; import "./compound/CompoundSavingsProtocol.sol"; contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); function borrowCaps(address) external virtual returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (public virtually) Sell, // sell an amount of some token (public virtually) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout {OnePrimary, TwoPrimary, PrimaryAndSecondary} enum MarketLayout {ZeroMarkets, OneMarket, TwoMarkets} struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Interest { struct Rate { uint256 value; } struct Index { uint96 borrow; uint96 supply; uint32 lastUpdate; } } library Monetary { struct Price { uint256 value; } struct Value { uint256 value; } } library Storage { // All information necessary for tracking a market struct Market { // Contract address of the associated ERC20 token address token; // Total aggregated supply and borrow amount of the entire market Types.TotalPar totalPar; // Interest index of the market Interest.Index index; // Contract address of the price oracle for this market address priceOracle; // Contract address of the interest setter for this market address interestSetter; // Multiplier on the marginRatio for this market Decimal.D256 marginPremium; // Multiplier on the liquidationSpread for this market Decimal.D256 spreadPremium; // Whether additional borrows are allowed for this market bool isClosing; } // The global risk parameters that govern the health and security of the system struct RiskParams { // Required ratio of over-collateralization Decimal.D256 marginRatio; // Percentage penalty incurred by liquidated accounts Decimal.D256 liquidationSpread; // Percentage of the borrower's interest fee that gets passed to the suppliers Decimal.D256 earningsRate; // The minimum absolute borrow value of an account // There must be sufficient incentivize to liquidate undercollateralized accounts Monetary.Value minBorrowedValue; } // The maximum RiskParam values that can be set struct RiskLimits { uint64 marginRatioMax; uint64 liquidationSpreadMax; uint64 earningsRateMax; uint64 marginPremiumMax; uint64 spreadPremiumMax; uint128 minBorrowedValueMax; } // The entire storage state of Solo struct State { // number of markets uint256 numMarkets; // marketId => Market mapping(uint256 => Market) markets; // owner => account number => Account mapping(address => mapping(uint256 => Account.Storage)) accounts; // Addresses that can control other users accounts mapping(address => mapping(address => bool)) operators; // Addresses that can control all users accounts mapping(address => bool) globalOperators; // mutable risk parameters of the system RiskParams riskParams; // immutable risk limits of the system RiskLimits riskLimits; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function ownerSetSpreadPremium( uint256 marketId, Decimal.D256 memory spreadPremium ) public virtual; function getIsGlobalOperator(address operator) public virtual view returns (bool); function getMarketTokenAddress(uint256 marketId) public virtual view returns (address); function ownerSetInterestSetter(uint256 marketId, address interestSetter) public virtual; function getAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketPriceOracle(uint256 marketId) public virtual view returns (address); function getMarketInterestSetter(uint256 marketId) public virtual view returns (address); function getMarketSpreadPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getNumMarkets() public virtual view returns (uint256); function ownerWithdrawUnsupportedTokens(address token, address recipient) public virtual returns (uint256); function ownerSetMinBorrowedValue(Monetary.Value memory minBorrowedValue) public virtual; function ownerSetLiquidationSpread(Decimal.D256 memory spread) public virtual; function ownerSetEarningsRate(Decimal.D256 memory earningsRate) public virtual; function getIsLocalOperator(address owner, address operator) public virtual view returns (bool); function getAccountPar(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Par memory); function ownerSetMarginPremium( uint256 marketId, Decimal.D256 memory marginPremium ) public virtual; function getMarginRatio() public virtual view returns (Decimal.D256 memory); function getMarketCurrentIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getMarketIsClosing(uint256 marketId) public virtual view returns (bool); function getRiskParams() public virtual view returns (Storage.RiskParams memory); function getAccountBalances(Account.Info memory account) public virtual view returns (address[] memory, Types.Par[] memory, Types.Wei[] memory); function renounceOwnership() public virtual; function getMinBorrowedValue() public virtual view returns (Monetary.Value memory); function setOperators(OperatorArg[] memory args) public virtual; function getMarketPrice(uint256 marketId) public virtual view returns (address); function owner() public virtual view returns (address); function isOwner() public virtual view returns (bool); function ownerWithdrawExcessTokens(uint256 marketId, address recipient) public virtual returns (uint256); function ownerAddMarket( address token, address priceOracle, address interestSetter, Decimal.D256 memory marginPremium, Decimal.D256 memory spreadPremium ) public virtual; function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getMarketWithInfo(uint256 marketId) public virtual view returns ( Storage.Market memory, Interest.Index memory, Monetary.Price memory, Interest.Rate memory ); function ownerSetMarginRatio(Decimal.D256 memory ratio) public virtual; function getLiquidationSpread() public virtual view returns (Decimal.D256 memory); function getAccountWei(Account.Info memory account, uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketTotalPar(uint256 marketId) public virtual view returns (Types.TotalPar memory); function getLiquidationSpreadForPair( uint256 heldMarketId, uint256 owedMarketId ) public virtual view returns (Decimal.D256 memory); function getNumExcessTokens(uint256 marketId) public virtual view returns (Types.Wei memory); function getMarketCachedIndex(uint256 marketId) public virtual view returns (Interest.Index memory); function getAccountStatus(Account.Info memory account) public virtual view returns (uint8); function getEarningsRate() public virtual view returns (Decimal.D256 memory); function ownerSetPriceOracle(uint256 marketId, address priceOracle) public virtual; function getRiskLimits() public virtual view returns (Storage.RiskLimits memory); function getMarket(uint256 marketId) public virtual view returns (Storage.Market memory); function ownerSetIsClosing(uint256 marketId, bool isClosing) public virtual; function ownerSetGlobalOperator(address operator, bool approved) public virtual; function transferOwnership(address newOwner) public virtual; function getAdjustedAccountValues(Account.Info memory account) public virtual view returns (Monetary.Value memory, Monetary.Value memory); function getMarketMarginPremium(uint256 marketId) public virtual view returns (Decimal.D256 memory); function getMarketInterestRate(uint256 marketId) public virtual view returns (Interest.Rate memory); } pragma solidity ^0.6.0; contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../DS/DSMath.sol"; abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { 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; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../compound/helpers/Exponential.sol"; import "../../interfaces/ERC20.sol"; contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } pragma solidity ^0.6.0; import "./CarefulMath.sol"; contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } pragma solidity ^0.6.0; contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ProtocolInterface.sol"; import "./ISoloMargin.sol"; import "../../interfaces/ERC20.sol"; import "../../DS/DSAuth.sol"; contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverV2 is AaveHelperV2, AdminAuth, DFSExchangeData { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xBBCD23145Ab10C369c9e5D3b1D58506B0cD2ab44; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant AETH_ADDRESS = 0x030bA81f1c18d280636F32af80b9AAd02Cf0854e; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, address market, uint256 rateMode, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,address,uint256,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(market, exchangeDataBytes, rateMode, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(address _market, bytes memory _exchangeDataBytes, uint256 _rateMode, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } else { functionData = abi.encodeWithSignature("boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256)", _market, exData, _rateMode, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @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 ILendingPoolAddressesProviderV2 { 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 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; } 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} } interface ILendingPoolV2 { /** * @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 **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @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 **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @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 (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } pragma solidity ^0.6.0; /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external virtual view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external virtual view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/GasBurner.sol"; abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } contract MCDCloseTaker is MCDSaverProxyHelper, GasBurner { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; ManagerType managerType; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( DFSExchangeData.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable burnGas(20) { mcdCloseFlashLoan.transfer(msg.value); // 0x fee address managerAddr = getManagerAddr(_closeData.managerType); if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).urns(_closeData.cdpId), Manager(managerAddr).ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(Manager(managerAddr), _closeData.cdpId, Manager(managerAddr).ilks(_closeData.cdpId)); } Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); bytes memory packedData = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(address(this), packedData); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); Manager(managerAddr).cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _managerAddr Address of the CDP Manager /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(address _managerAddr, uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(Manager(_managerAddr), _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, DFSExchangeData.ExchangeData memory _exchangeData ) internal pure returns (bytes memory) { return abi.encode(_closeData, _exchangeData); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILoanShifter.sol"; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../mcd/create/MCDCreateProxyActions.sol"; contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; Manager manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(address(manager), _cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(address(manager), _cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(address(manager), _cdpId, _joinAddr, collAmount); // draw debt drawDai(address(manager), _cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } pragma solidity ^0.6.0; abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "./MCDCreateProxyActions.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/Manager.sol"; import "../../interfaces/Join.sol"; import "../../DS/DSProxy.sol"; import "./MCDCreateTaker.sol"; contract MCDCreateFlashLoan is DFSExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCreateTaker.CreateData memory createData, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCreateTaker.CreateData,ExchangeData)); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxy(payable(proxy)).owner(); openAndLeverage(createData.collAmount, createData.daiAmount + _fee, createData.joinAddr, proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, (_collAmount + collSwaped)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "./SafeERC20.sol"; interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./saver/MCDSaverProxyHelper.sol"; import "../interfaces/Spotter.sol"; contract MCDLoanInfo is MCDSaverProxyHelper { Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public constant vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public constant spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); struct VaultInfo { address owner; uint256 ratio; uint256 collateral; uint256 debt; bytes32 ilk; address urn; } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getVaultInfo(uint _cdpId) public view returns (VaultInfo memory vaultInfo) { address urn = manager.urns(_cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint256 collateral, uint256 debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); vaultInfo = VaultInfo({ owner: manager.owns(_cdpId), ratio: getRatio(_cdpId, ilk), collateral: collateral, debt: debt, ilk: ilk, urn: urn }); } function getVaultInfos(uint256[] memory _cdps) public view returns (VaultInfo[] memory vaultInfos) { vaultInfos = new VaultInfo[](_cdps.length); for (uint256 i = 0; i < _cdps.length; i++) { vaultInfos[i] = getVaultInfo(_cdps[i]); } } function getRatios(uint256[] memory _cdps) public view returns (uint[] memory ratios) { ratios = new uint256[](_cdps.length); for (uint256 i = 0; i<_cdps.length; i++) { bytes32 ilk = manager.ilks(_cdps[i]); ratios[i] = getRatio(_cdps[i], ilk); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "./StaticV2.sol"; import "../saver/MCDSaverProxy.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../auth/AdminAuth.sol"; /// @title Handles subscriptions for automatic monitoring contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } pragma solidity ^0.6.0; /// @title Implements enum Method abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } pragma solidity ^0.6.0; import "../../interfaces/Join.sol"; import "../../interfaces/ERC20.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Flipper.sol"; import "../../interfaces/Gem.sol"; contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); if(Join(_joinAddr).dec() != 18) { amount = amount / (10**(18 - Join(_joinAddr).dec())); } Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } pragma solidity ^0.6.0; abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/Manager.sol"; import "../../interfaces/Vat.sol"; import "../../interfaces/Spotter.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; import "../../utils/BotRegistry.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./ISubscriptionsV2.sol"; import "./StaticV2.sol"; import "./MCDMonitorProxyV2.sol"; /// @title Implements logic that allows bots to call Boost and Repay contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1000000; uint public BOOST_GAS_COST = 1000000; bytes4 public REPAY_SELECTOR = 0xf360ce20; bytes4 public BOOST_SELECTOR = 0x8ec2ae25; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant PROXY_PERMISSION_ADDR = 0x5a4f877CA808Cca3cB7c2A194F80Ab8588FAE26B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(REPAY_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( DFSExchangeData.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSelector(BOOST_SELECTOR, _exchangeData, _cdpId, gasCost, _joinAddr, 0)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./StaticV2.sol"; abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Implements logic for calling MCDSaverProxy always from same contract contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; uint public MIN_CHANGE_PERIOD = 6 * 1 hours; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > MIN_CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "../../compound/helpers/Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for cream contracts contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } pragma solidity ^0.6.0; abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } pragma solidity ^0.6.0; abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CreamSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "../utils/ZrxAllowlist.sol"; import "./SaverExchangeHelper.sol"; import "./SaverExchangeRegistry.sol"; contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } pragma solidity ^0.6.0; import "../utils/SafeERC20.sol"; import "../utils/Discount.sol"; contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/Discount.sol"; import "../helpers/CompoundSaverHelper.sol"; import "../../loggers/DefisaverLogger.sol"; /// @title Implements the actual logic of Repay/Boost with FL contract CompoundSaverFlashProxy is DFSExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee _exData.srcAmount = (borrowAmount + _flashLoanData[0]); _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } pragma solidity ^0.6.0; import "../../interfaces/CEtherInterface.sol"; import "../../interfaces/CompoundOracleInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../utils/Discount.sol"; import "../../DS/DSMath.sol"; import "../../DS/DSProxy.sol"; import "./Exponential.sol"; import "../../utils/BotRegistry.sol"; import "../../utils/SafeERC20.sol"; /// @title Utlity functions for Compound contracts contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (tokenAddr == ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; import "../../compound/helpers/CompoundSaverHelper.sol"; contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, DFSExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _exData.user = user; _exData.srcAmount = borrowAmount; (, swapAmount) = _sell(_exData); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "../utils/FlashLoanReceiverBase.sol"; import "../interfaces/DSProxyInterface.sol"; import "../exchangeV3/DFSExchangeCore.sol"; import "./ShifterRegistry.sol"; import "./LoanShifterTaker.sol"; /// @title LoanShifterReceiver Recevies the Aave flash loan and calls actions through users DSProxy contract LoanShifterReceiver is DFSExchangeCore, FlashLoanReceiverBase, AdminAuth { address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant SERVICE_FEE = 400; // 0.25% Fee ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendTokenToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(paramData.proxy).owner(); if (paramData.swapType == 1) { // COLL_SWAP (, uint256 amount) = _sell(exchangeData); sendTokenAndEthToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendTokenToProxy( payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this)) ); } else { // NO_SWAP just send tokens to proxy sendTokenAndEthToProxy( payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr) ); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall( uint256 _amount, uint256 _fee, bytes memory _params ) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { LoanShifterTaker.LoanShiftData memory shiftData; address proxy; (shiftData, exchangeData, proxy) = abi.decode( _params, (LoanShifterTaker.LoanShiftData, ExchangeData, address) ); bytes memory proxyData1; bytes memory proxyData2; uint256 openDebtAmount = (_amount + _fee); if (shiftData.fromProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER FROM proxyData1 = abi.encodeWithSignature( "close(uint256,address,uint256,uint256)", shiftData.id1, shiftData.addrLoan1, _amount, shiftData.collAmount ); } else if (shiftData.fromProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND FROM if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature( "changeDebt(address,address,uint256,uint256)", shiftData.debtAddr1, shiftData.debtAddr2, _amount, exchangeData.srcAmount ); } else { proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", shiftData.addrLoan1, shiftData.debtAddr1, shiftData.collAmount, shiftData.debtAmount ); } } if (shiftData.toProtocol == LoanShifterTaker.Protocols.MCD) { // MAKER TO proxyData2 = abi.encodeWithSignature( "open(uint256,address,uint256)", shiftData.id2, shiftData.addrLoan2, openDebtAmount ); } else if (shiftData.toProtocol == LoanShifterTaker.Protocols.COMPOUND) { // COMPOUND TO if (shiftData.swapType == LoanShifterTaker.SwapType.DEBT_SWAP) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", shiftData.debtAddr2); } else { proxyData2 = abi.encodeWithSignature( "open(address,address,uint256)", shiftData.addrLoan2, shiftData.debtAddr2, openDebtAmount ); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: shiftData.debtAddr1, protocol1: uint8(shiftData.fromProtocol), protocol2: uint8(shiftData.toProtocol), swapType: uint8(shiftData.swapType) }); } function sendTokenAndEthToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function sendTokenToProxy( address payable _proxy, address _reserve, uint256 _amount ) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } else { _proxy.transfer(address(this).balance); } } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external payable override(FlashLoanReceiverBase, DFSExchangeCore) {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../DS/DSProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../shifter/ShifterRegistry.sol"; import "./CompoundCreateTaker.sol"; /// @title Contract that receives the FL from Aave for Creating loans contract CompoundCreateReceiver is FlashLoanReceiverBase, DFSExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = DSProxyInterface(compCreate.proxyAddr).owner(); _sell(exchangeData); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { CompoundCreateTaker.CreateInfo memory createData; address proxy; (createData , exchangeData, proxy)= abi.decode(_params, (CompoundCreateTaker.CreateInfo, ExchangeData, address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", createData.cCollAddress, createData.cBorrowAddress, (_amount + _fee)); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: createData.cCollAddress, cDebtAddr: createData.cBorrowAddress }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "../../utils/SafeERC20.sol"; /// @title Opens compound positions with a leverage contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, DFSExchangeData.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); bytes memory paramsData = abi.encode(_createInfo, _exchangeData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/ProxyPermission.sol"; import "../utils/DydxFlashLoanBase.sol"; import "../loggers/DefisaverLogger.sol"; import "../interfaces/ERC20.sol"; /// @title Takes flash loan contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../utils/SafeMath.sol"; import "../savings/dydx/ISoloMargin.sol"; contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../AaveHelperV2.sol"; import "../../../utils/GasBurner.sol"; import "../../../auth/AdminAuth.sol"; import "../../../auth/ProxyPermission.sol"; import "../../../utils/DydxFlashLoanBase.sol"; import "../../../loggers/DefisaverLogger.sol"; import "../../../interfaces/ProxyRegistryInterface.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../interfaces/ERC20.sol"; import "../../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerOV2 is ProxyPermission, GasBurner, DFSExchangeData, AaveHelperV2 { address payable public constant AAVE_RECEIVER = 0xB33BBa30b6d276167C42d14fF3500FD24b4766D2; // leaving _flAmount to be the same as the older version function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; // for repay we are using regular flash loan with paying back the flash loan + premium uint256[] memory modes = new uint256[](1); modes[0] = 0; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, true, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } // leaving _flAmount to be the same as the older version function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable burnGas(10) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); // send msg.value for exchange to the receiver AAVE_RECEIVER.transfer(msg.value); address[] memory assets = new address[](1); assets[0] = _data.srcAddr; uint256[] memory amounts = new uint256[](1); amounts[0] = _data.srcAmount; uint256[] memory modes = new uint256[](1); modes[0] = _rateMode; // create data bytes memory encodedData = packExchangeData(_data); bytes memory data = abi.encode(encodedData, _market, _gasCost, _rateMode, false, address(this)); // give permission to receiver and execute tx givePermission(AAVE_RECEIVER); ILendingPoolV2(lendingPool).flashLoan(AAVE_RECEIVER, assets, amounts, modes, address(this), data, AAVE_REFERRAL_CODE); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; import "./DSProxyInterface.sol"; abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } pragma solidity ^0.6.0; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/OasisInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapExchangeInterface.sol"; import "../../interfaces/UniswapFactoryInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } pragma solidity ^0.6.0; import "./ERC20.sol"; abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } pragma solidity ^0.6.0; abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } pragma solidity ^0.6.0; abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV3.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/UniswapRouterInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; /// @title DFS exchange wrapper for UniswapV2 contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV3.sol"; import "../utils/SafeERC20.sol"; contract DFSPrices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; import "../../utils/SafeERC20.sol"; import "../../interfaces/KyberNetworkProxyInterface.sol"; import "../../interfaces/ExchangeInterfaceV2.sol"; import "../../interfaces/IFeeRecipient.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, walletAddr ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); address walletAddr = feeRecipient.getFeeAddr(); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, walletAddr ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "../interfaces/IFeeRecipient.sol"; import "./SaverExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee IFeeRecipient public constant _feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { address walletAddr = _feeRecipient.getFeeAddr(); feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_token).safeTransfer(walletAddr, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../exchange/SaverExchangeCore.sol"; contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; ManagerType managerType; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay, uint8 managerType ) = abi.decode(_params, (bytes,uint256,uint256,address,bool,uint8)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr, managerType: ManagerType(managerType) }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId)); uint daiDrawn = drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), maxDebt); // Swap _exchangeData.srcAmount = daiDrawn + _saverData.loanAmount - takeFee(_saverData.gasCost, daiDrawn + _saverData.loanAmount); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(managerAddr, _saverData.cdpId, Manager(managerAddr).ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address managerAddr = getManagerAddr(_saverData.managerType); address user = getOwner(Manager(managerAddr), _saverData.cdpId); bytes32 ilk = Manager(managerAddr).ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(managerAddr, _saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); _exchangeData.user = user; _exchangeData.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; (, uint paybackAmount) = _sell(_exchangeData); paybackAmount -= takeFee(_saverData.gasCost, paybackAmount); paybackAmount = limitLoanAmount(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(managerAddr, _saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(managerAddr, _saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, user, _exchangeData.srcAmount, paybackAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), Manager(_managerAddr).urns(_cdpId), Manager(_managerAddr).urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../mcd/saver/MCDSaverProxy.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../auth/AdminAuth.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../mcd/saver/MCDSaverProxyHelper.sol"; import "./MCDCloseTaker.sol"; contract MCDCloseFlashLoan is DFSExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { (address proxy, bytes memory packedData) = abi.decode(_params, (address,bytes)); (MCDCloseTaker.CloseData memory closeDataSent, ExchangeData memory exchangeData) = abi.decode(packedData, (MCDCloseTaker.CloseData,ExchangeData)); CloseData memory closeData = CloseData({ cdpId: closeDataSent.cdpId, collAmount: closeDataSent.collAmount, daiAmount: closeDataSent.daiAmount, minAccepted: closeDataSent.minAccepted, joinAddr: closeDataSent.joinAddr, proxy: proxy, flFee: _fee, toDai: closeDataSent.toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); exchangeData.dfsFeeDivider = SERVICE_FEE; exchangeData.user = user; address managerAddr = getManagerAddr(closeDataSent.managerType); closeCDP(closeData, exchangeData, user, managerAddr); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user, address _managerAddr ) internal { paybackDebt(_managerAddr, _closeData.cdpId, Manager(_managerAddr).ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_managerAddr, _closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); } else { _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee); (, daiSwaped) = _buy(_exchangeData); } address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(address _managerAddr, uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { Manager(_managerAddr).frob(_cdpId, -toPositiveInt(_amount), 0); Manager(_managerAddr).flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(address _managerAddr, uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = Manager(_managerAddr).urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); Manager(_managerAddr).frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == EXCHANGE_WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, DFSExchangeCore) payable {} } pragma solidity ^0.6.0; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Imports cream position from the account to DSProxy contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } pragma solidity ^0.6.0; import "../../utils/GasBurner.sol"; import "../../auth/ProxyPermission.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ILendingPool.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Imports Compound position from the account to DSProxy contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x1DB68Ba0B85800FD323387E8B69d9AE867e00B94; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve DSProxy to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, address(this)); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } } pragma solidity ^0.6.0; import "../../auth/AdminAuth.sol"; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../utils/SafeERC20.sol"; /// @title Receives FL from Aave and imports the position to DSProxy contract CompoundImportFlashLoan is FlashLoanReceiverBase, AdminAuth { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params ) external override { (address cCollAddr, address cBorrowAddr, address proxy) = abi.decode(_params, (address, address, address)); address user = DSProxyInterface(proxy).owner(); uint256 usersCTokenBalance = CTokenInterface(cCollAddr).balanceOf(user); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowAddr, _amount); // repay compound debt on behalf of the user require( CTokenInterface(cBorrowAddr).repayBorrowBehalf(user, uint256(-1)) == 0, "Repay borrow behalf fail" ); bytes memory depositProxyCallData = formatDSProxyPullTokensCall(cCollAddr, usersCTokenBalance); DSProxyInterface(proxy).execute(PULL_TOKENS_PROXY, depositProxyCallData); // borrow debt now on ds proxy bytes memory borrowProxyCallData = formatDSProxyBorrowCall(cCollAddr, cBorrowAddr, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, borrowProxyCallData); // repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call to pull tokens to DSProxy /// @param _cTokenAddr CToken address of the collateral /// @param _amount Amount of cTokens to pull function formatDSProxyPullTokensCall( address _cTokenAddr, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "pullTokens(address,uint256)", _cTokenAddr, _amount ); } /// @notice Formats function data call borrow through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed function formatDSProxyBorrowCall( address _cCollToken, address _cBorrowToken, address _borrowToken, uint256 _amount ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount ); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTakerV2 is DydxFlashLoanBase, ProxyPermission, GasBurner, DFSExchangeData { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x5a7689F1452d57E92878e0c0Be47cA3525e8Fcc9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode,_gasCost, true, _flAmount); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint256 _gasCost, uint _flAmount) public payable { _flashLoan(_market, _data, _rateMode, _gasCost, false, _flAmount); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost, bool _isRepay, uint _flAmount) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = _flAmount; // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _market, _rateMode, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTakerV2 is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x1C9B7FBD410Adcd213C5d6CBA12e651300061eaD; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _market Market in which we want to import /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _market, address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_market, _collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../auth/AdminAuth.sol"; import "../../auth/ProxyPermission.sol"; import "../../utils/DydxFlashLoanBase.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/ProxyRegistryInterface.sol"; import "../../interfaces/TokenInterface.sol"; import "../../interfaces/ERC20.sol"; /// @title Import Aave position from account to wallet /// @dev Contract needs to have enough wei in WETH for all transactions (2 WETH wei per transaction) contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x5cD4239D2AA5b487bA87c3715127eA53685B4926; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve DSProxy to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } pragma solidity ^0.6.0; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "../compound/helpers/Exponential.sol"; contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../helpers/Exponential.sol"; import "../../utils/SafeERC20.sol"; import "../../utils/GasBurner.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface( 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B ); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim( address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow ) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint256) { uint256 compBalance = 0; for (uint256 i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance = add_(comp.compAccrued(_user), compBalance); compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getClaimableAssets(address[] memory _cTokens, address _user) public view returns (bool[] memory supplyClaims, bool[] memory borrowClaims) { supplyClaims = new bool[](_cTokens.length); borrowClaims = new bool[](_cTokens.length); for (uint256 i = 0; i < _cTokens.length; ++i) { supplyClaims[i] = getSuppyBalance(_cTokens[i], _user) > 0; borrowClaims[i] = getBorrowBalance(_cTokens[i], _user) > 0; } } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint256 supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: comp.compSupplierIndex(_cToken, _supplier) }); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = supplierDelta; } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint256 borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: comp.compBorrowerIndex(_cToken, _borrower) }); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_( CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex ); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = borrowerDelta; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompBalance.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../CompoundBasicProxy.sol"; contract CompLeverage is DFSExchangeCore, CompBalance { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.user = msg.sender; exchangeData.dfsFeeDivider = 400; // 0.25% exchangeData.srcAmount = compBalance; (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { if (exchangeData.destAddr != ETH_ADDRESS) { ERC20(exchangeData.destAddr).safeTransfer(msg.sender, depositAmount); } else { msg.sender.transfer(address(this).balance); } } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); // reverts on fail } } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic compound interactions through the DSProxy contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; import "../interfaces/CTokenInterface.sol"; import "../interfaces/CEtherInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; /// @title Basic cream interactions through the DSProxy contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/CompoundOracleInterface.sol"; import "../interfaces/ComptrollerInterface.sol"; import "../interfaces/CTokenInterface.sol"; import "./helpers/Exponential.sol"; contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CompoundSafetyRatio.sol"; import "./helpers/CompoundSaverHelper.sol"; /// @title Gets data about Compound positions contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; uint borrowCap; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]), borrowCap: comp.borrowCaps(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/BotRegistry.sol"; import "../../utils/GasBurner.sol"; import "./CompoundMonitorProxy.sol"; import "./CompoundSubscriptions.sol"; import "../../interfaces/GasTokenInterface.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../CompoundSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1500000; uint public BOOST_GAS_COST = 1000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeCompoundFlashLoanTaker(address _newCompoundFlashLoanTakerAddress) public onlyAdmin { compoundFlashLoanTakerAddress = _newCompoundFlashLoanTakerAddress; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Compound automatization contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../interfaces/GasTokenInterface.sol"; import "./DFSExchangeCore.sol"; import "../DS/DSMath.sol"; import "../loggers/DefisaverLogger.sol"; import "../auth/AdminAuth.sol"; import "../utils/GasBurner.sol"; import "../utils/SafeERC20.sol"; contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; exData.user = _user; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./DFSExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DFSExchange dfsExchange = DFSExchange(0xc2Ce04e2FB4DD20964b4410FcE718b95963a1587); function callSell(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(DFSExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); dfsExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(dfsExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { dfsExchange = DFSExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./CreamSafetyRatio.sol"; import "./helpers/CreamSaverHelper.sol"; /// @title Gets data about cream positions contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } pragma solidity ^0.6.0; import "../../interfaces/ERC20.sol"; import "../../interfaces/CTokenInterface.sol"; import "../../interfaces/ComptrollerInterface.sol"; import "../../utils/SafeERC20.sol"; contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/FlashLoanReceiverBase.sol"; import "../../interfaces/DSProxyInterface.sol"; import "../../exchangeV3/DFSExchangeData.sol"; /// @title Contract that receives the FL from Aave for Repays/Boost contract CompoundSaverFlashLoan is FlashLoanReceiverBase, DFSExchangeData { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcaB974d1702a056e6FF16f1DaA34646E41Ef485E; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(FlashLoanReceiverBase) payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../exchange/SaverExchangeCore.sol"; import "../../loggers/DefisaverLogger.sol"; import "../helpers/CreamSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CreamSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../DS/DSProxy.sol"; import "../utils/Discount.sol"; import "../interfaces/IFeeRecipient.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPool.sol"; import "../interfaces/ILendingPoolAddressesProvider.sol"; import "../interfaces/IPriceOracleGetterAave.sol"; import "../utils/SafeERC20.sol"; import "../utils/BotRegistry.sol"; contract AaveHelper is DSMath { using SafeERC20 for ERC20; IFeeRecipient public constant feeRecipient = IFeeRecipient(0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A); address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost == 0) return 0; address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } address walletAddr = feeRecipient.getFeeAddr(); if (_tokenAddr == ETH_ADDR) { payable(walletAddr).transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(walletAddr, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function isAutomation() internal view returns(bool) { return BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelper.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/ILendingPool.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxy is GasBurner, DFSExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.dfsFeeDivider = isAutomation() ? AUTOMATIC_SERVICE_FEE : MANUAL_SERVICE_FEE; _data.user = user; // swap (, destAmount) = _sell(_data); destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } else { destAmount = _data.srcAmount; destAmount -= getGasCost(_data.destAmount, user, _gasCost, _data.destAddr); } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../AaveHelperV2.sol"; import "../../exchangeV3/DFSExchangeCore.sol"; import "../../interfaces/IAToken.sol"; import "../../interfaces/TokenInterface.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../utils/GasBurner.sol"; contract AaveSaverProxyV2 is DFSExchangeCore, AaveHelperV2, GasBurner { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; function repay(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); ILendingPoolV2(lendingPool).withdraw(_data.srcAddr, _data.srcAmount, address(this)); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // swap (, destAmount) = _sell(_data); } // take gas cost at the end destAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); // if destAmount higher than borrow repay whole debt uint borrow; if (_rateMode == STABLE_ID) { (,borrow,,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } else { (,,borrow,,,,,,) = dataProvider.getUserReserveData(_data.destAddr, address(this)); } ILendingPoolV2(lendingPool).repay(_data.destAddr, destAmount > borrow ? borrow : destAmount, _rateMode, payable(address(this))); // first return 0x fee to tx.origin as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Repay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(address _market, ExchangeData memory _data, uint _rateMode, uint _gasCost) public payable burnGas(20) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address payable user = payable(getUserAddress()); // borrow amount ILendingPoolV2(lendingPool).borrow(_data.srcAddr, _data.srcAmount, _rateMode, AAVE_REFERRAL_CODE, address(this)); // take gas cost at the beginning _data.srcAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), _data.srcAmount, user, _gasCost, _data.srcAddr); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.user = user; _data.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { _data.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } (, destAmount) = _sell(_data); } else { destAmount = _data.srcAmount; } if (_data.destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit.value(destAmount)(); } approveToken(_data.destAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_data.destAddr, destAmount, address(this), AAVE_REFERRAL_CODE); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_data.destAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveV2Boost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../utils/SafeERC20.sol"; import "../../../interfaces/TokenInterface.sol"; import "../../../DS/DSProxy.sol"; import "../../AaveHelperV2.sol"; import "../../../auth/AdminAuth.sol"; import "../../../exchangeV3/DFSExchangeCore.sol"; /// @title Import Aave position from account to wallet contract AaveSaverReceiverOV2 is AaveHelperV2, AdminAuth, DFSExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; function boost(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy) internal { (, uint swappedAmount) = _sell(_exchangeData); address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve users proxy to pull tokens uint256 msgValue = 0; address token = _exchangeData.destAddr; // sell always return eth, but deposit differentiate eth vs weth, so we change weth address to eth when we are depoisting if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { msgValue = swappedAmount; token = ETH_ADDR; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // deposit collateral on behalf of user DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "deposit(address,address,uint256)", _market, token, swappedAmount ) ); } function repay(ExchangeData memory _exchangeData, address _market, uint256 _gasCost, address _proxy, uint256 _rateMode, uint _aaveFlashlLoanFee) internal { // we will withdraw exactly the srcAmount, as fee we keep before selling uint valueToWithdraw = _exchangeData.srcAmount; // take out the fee wee need to pay and sell the rest _exchangeData.srcAmount = _exchangeData.srcAmount - _aaveFlashlLoanFee; (, uint swappedAmount) = _sell(_exchangeData); // set protocol fee left to eth balance of this address // but if destAddr is eth or weth, this also includes that value so we need to substract it uint protocolFeeLeft = address(this).balance; address user = DSAuth(_proxy).owner(); swappedAmount -= getGasCost(ILendingPoolAddressesProviderV2(_market).getPriceOracle(), swappedAmount, user, _gasCost, _exchangeData.destAddr); // if its eth we need to send it to the basic proxy, if not, we need to approve basic proxy to pull tokens uint256 msgValue = 0; if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { protocolFeeLeft -= swappedAmount; msgValue = swappedAmount; } else { ERC20(_exchangeData.destAddr).safeApprove(_proxy, swappedAmount); } // first payback the loan with swapped amount DSProxy(payable(_proxy)).execute{value: msgValue}( AAVE_BASIC_PROXY, abi.encodeWithSignature( "payback(address,address,uint256,uint256)", _market, _exchangeData.destAddr, swappedAmount, _rateMode ) ); // if some tokens left after payback (full repay) we need to return it back to the proxy owner require(user != address(0)); // be sure that we fetched the user correctly if (_exchangeData.destAddr == ETH_ADDR || _exchangeData.destAddr == WETH_ADDRESS) { // keep protocol fee for tx.origin, but the rest of the balance return to the user payable(user).transfer(address(this).balance - protocolFeeLeft); } else { // in case its a token, just return whole value back to the user, as protocol fee is always in eth uint amount = ERC20(_exchangeData.destAddr).balanceOf(user); ERC20(_exchangeData.destAddr).safeTransfer(user, amount); } // pull the amount we flash loaned in collateral to be able to payback the debt DSProxy(payable(_proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", _market, _exchangeData.srcAddr, valueToWithdraw)); } function executeOperation( address[] calldata, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) public returns (bool) { ( bytes memory exchangeDataBytes, address market, uint256 gasCost, uint256 rateMode, bool isRepay, address proxy ) = abi.decode(params, (bytes,address,uint256,uint256,bool,address)); require(initiator == proxy, "initiator isn't proxy"); ExchangeData memory exData = unpackExchangeData(exchangeDataBytes); exData.user = DSAuth(proxy).owner(); exData.dfsFeeDivider = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { exData.dfsFeeDivider = AUTOMATIC_SERVICE_FEE; } // this is to avoid stack too deep uint fee = premiums[0]; uint totalValueToReturn = exData.srcAmount + fee; // if its repay, we are using regular flash loan and payback the premiums if (isRepay) { repay(exData, market, gasCost, proxy, rateMode, fee); address token = exData.srcAddr; if (token == ETH_ADDR || token == WETH_ADDRESS) { // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(totalValueToReturn)(); token = WETH_ADDRESS; } ERC20(token).safeApprove(ILendingPoolAddressesProviderV2(market).getLendingPool(), totalValueToReturn); } else { boost(exData, market, gasCost, proxy); } tx.origin.transfer(address(this).balance); return true; } /// @dev allow contract to receive eth from sell receive() external override payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelperV2.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImportV2 is AaveHelperV2, AdminAuth { using SafeERC20 for ERC20; address public constant BASIC_PROXY = 0xc17c8eB12Ba24D62E69fd57cbd504EEf418867f9; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address market, address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(market); uint256 globalBorrowAmountStable = 0; uint256 globalBorrowAmountVariable = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,address,uint256)", market, ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(borrowToken, user); if (borrowsStable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsStable, STABLE_ID)); globalBorrowAmountStable = borrowsStable; } if (borrowsVariable > 0) { DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,address,uint256,uint256)", market, borrowToken, borrowsVariable, VARIABLE_ID)); globalBorrowAmountVariable = borrowsVariable; } } if (globalBorrowAmountVariable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountVariable, borrowToken, user, VARIABLE_ID); } if (globalBorrowAmountStable > 0) { paybackOnBehalf(market, proxy, globalBorrowAmountStable, borrowToken, user, STABLE_ID); } (address aToken,,) = dataProvider.getReserveTokensAddresses(collateralToken); // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aToken, ERC20(aToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address,address)", market, collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256)", market, ETH_ADDR, ethAmount)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function paybackOnBehalf(address _market, address _proxy, uint _amount, address _token, address _onBehalf, uint _rateMode) internal { // payback on behalf of user if (_token != ETH_ADDR) { ERC20(_token).safeApprove(_proxy, _amount); DSProxy(payable(_proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } else { DSProxy(payable(_proxy)).execute{value: _amount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,uint256,address)", _market, _token, _amount, _rateMode, _onBehalf)); } } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelperV2.sol"; import "../interfaces/ILendingPoolV2.sol"; contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../exchangeV3/DFSExchangeData.sol"; import "./AaveMonitorProxyV2.sol"; import "./AaveSubscriptionsV2.sol"; import "../AaveSafetyRatioV2.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitorV2 is AdminAuth, DSMath, AaveSafetyRatioV2, GasBurner { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorV2"; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant AAVE_MARKET_ADDRESS = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; AaveMonitorProxyV2 public aaveMonitorProxy; AaveSubscriptionsV2 public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxyV2(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptionsV2(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepayV2", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( DFSExchangeData.ExchangeData memory _exData, address _user, uint256 _rateMode, uint256 _flAmount ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost(address,(address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),uint256,uint256,uint256)", AAVE_MARKET_ADDRESS, _exData, _rateMode, gasCost, _flAmount ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoostV2", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptionsV2.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptionsV2.AaveHolder memory holder; holder = subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(AAVE_MARKET_ADDRESS, _user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxyV2 is AdminAuth { using SafeERC20 for ERC20; string public constant NAME = "AaveMonitorProxyV2"; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 hours; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Owner is able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyOwner { require(monitor == address(0)); monitor = _monitor; } /// @notice Owner is able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyOwner { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point owner is able to cancel monitor change function cancelMonitorChange() public onlyOwner { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyOwner { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyOwner { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } function setChangePeriod(uint _periodInHours) public onlyOwner { require(_periodInHours * 1 hours > CHANGE_PERIOD); CHANGE_PERIOD = _periodInHours * 1 hours; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptionsV2 is AdminAuth { string public constant NAME = "AaveSubscriptionsV2"; struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; import "../utils/GasBurner.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/IAToken.sol"; import "../interfaces/ILendingPoolV2.sol"; import "./AaveHelperV2.sol"; import "../utils/SafeERC20.sol"; /// @title Basic compound interactions through the DSProxy contract AaveBasicProxyV2 is GasBurner, AaveHelperV2 { using SafeERC20 for ERC20; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _market, address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); if (_tokenAddr == ETH_ADDR) { require(msg.value == _amount); TokenInterface(WETH_ADDRESS).deposit{value: _amount}(); _tokenAddr = WETH_ADDRESS; } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).deposit(_tokenAddr, _amount, address(this), AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_market, _tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be withdrawn /// @param _amount Amount of tokens to be withdrawn -> send -1 for whole amount function withdraw(address _market, address _tokenAddr, uint256 _amount) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { // if weth, pull to proxy and return ETH to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, address(this)); // needs to use balance of in case that amount is -1 for whole debt TokenInterface(WETH_ADDRESS).withdraw(TokenInterface(WETH_ADDRESS).balanceOf(address(this))); msg.sender.transfer(address(this).balance); } else { // if not eth send directly to user ILendingPoolV2(lendingPool).withdraw(_tokenAddr, _amount, msg.sender); } } /// @notice User borrows tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for stable rate and 2 for variable function borrow(address _market, address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); ILendingPoolV2(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE, address(this)); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function payback(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).balanceOf(msg.sender)); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, payable(address(this))); if (_tokenAddr == WETH_ADDRESS) { // Pull if we have any eth leftover TokenInterface(WETH_ADDRESS).withdraw(ERC20(WETH_ADDRESS).balanceOf(address(this))); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _market address provider for specific market /// @param _tokenAddr The address of the token to be paybacked /// @param _amount Amount of tokens to be payed back function paybackOnBehalf(address _market, address _tokenAddr, uint256 _amount, uint256 _rateMode, address _onBehalf) public burnGas(3) payable { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); _tokenAddr = changeToWeth(_tokenAddr); if (_tokenAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).deposit{value: msg.value}(); } else { uint amountToPull = min(_amount, ERC20(_tokenAddr).allowance(msg.sender, address(this))); ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amountToPull); } approveToken(_tokenAddr, lendingPool); ILendingPoolV2(lendingPool).repay(_tokenAddr, _amount, _rateMode, _onBehalf); if (_tokenAddr == WETH_ADDRESS) { // we do this so the user gets eth instead of weth TokenInterface(WETH_ADDRESS).withdraw(_amount); _tokenAddr = ETH_ADDR; } withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } function setUserUseReserveAsCollateralIfNeeded(address _market, address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); (,,,,,,,,bool collateralEnabled) = dataProvider.getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _market, address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } // stable = 1, variable = 2 function swapBorrowRateMode(address _market, address _reserve, uint _rateMode) public { address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool(); ILendingPoolV2(lendingPool).swapBorrowRateMode(_reserve, _rateMode); } function changeToWeth(address _token) private view returns(address) { if (_token == ETH_ADDR) { return WETH_ADDRESS; } return _token; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatioV2.sol"; import "../interfaces/IAaveProtocolDataProviderV2.sol"; contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; uint256 stableBorrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,userTokens[i].stableBorrowRate,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_market, _users[i]); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../savings/dydx/ISoloMargin.sol"; import "../../utils/SafeERC20.sol"; import "../../interfaces/TokenInterface.sol"; import "../../DS/DSProxy.sol"; import "../AaveHelper.sol"; import "../../auth/AdminAuth.sol"; // weth->eth // deposit eth for users proxy // borrow users token from proxy // repay on behalf of user // pull user supply // take eth amount from supply (if needed more, borrow it?) // return eth to sender /// @title Import Aave position from account to wallet contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0xF499FB2feb3351aEA373723a6A0e8F6BE6fBF616; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; address public constant PULL_TOKENS_PROXY = 0x45431b79F783e0BF0fe7eF32D06A3e061780bfc4; function callFunction( address, Account.Info memory, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address proxy ) = abi.decode(data, (address,address,uint256,address)); address user = DSProxy(payable(proxy)).owner(); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); uint256 globalBorrowAmount = 0; { // avoid stack too deep // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); globalBorrowAmount = borrowAmount; } // payback on behalf of user if (borrowToken != ETH_ADDR) { ERC20(borrowToken).safeApprove(proxy, globalBorrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } else { DSProxy(payable(proxy)).execute{value: globalBorrowAmount}(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); } // pull coll tokens DSProxy(payable(proxy)).execute(PULL_TOKENS_PROXY, abi.encodeWithSignature("pullTokens(address,uint256)", aCollateralToken, ERC20(aCollateralToken).balanceOf(user))); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit{value: (address(this).balance)}(); } } } pragma solidity ^0.6.0; import "./AaveHelper.sol"; contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "./AaveMonitorProxy.sol"; import "./AaveSubscriptions.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../../loggers/DefisaverLogger.sol"; import "../AaveSafetyRatio.sol"; import "../../exchange/SaverExchangeCore.sol"; /// @title Contract implements logic of calling boost/repay in the automatic system contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint public MAX_GAS_PRICE = 400000000000; // 400 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice As the code is new, have a emergancy admin saver proxy change function changeAaveSaverProxy(address _newAaveSaverProxy) public onlyAdmin { aaveSaverProxy = _newAaveSaverProxy; } /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } pragma solidity ^0.6.0; import "../../interfaces/DSProxyInterface.sol"; import "../../utils/SafeERC20.sol"; import "../../auth/AdminAuth.sol"; /// @title Contract with the actuall DSProxy permission calls the automation operations contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../auth/AdminAuth.sol"; /// @title Stores subscription information for Aave automatization contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./AaveSafetyRatio.sol"; contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; uint256 borrowRate; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,userTokens[i].borrowRate,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]) + ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsStable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } pragma solidity ^0.6.0; import "../DS/DSMath.sol"; import "../interfaces/TokenInterface.sol"; import "../interfaces/ExchangeInterfaceV2.sol"; import "./SaverExchangeHelper.sol"; contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../auth/AdminAuth.sol"; import "./SaverExchange.sol"; import "../utils/SafeERC20.sol"; contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ZeroxWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); /// @dev 0x always uses max approve in v1, so we approve the exact amount we want to sell /// @dev safeApprove is modified to always first set approval to 0, then to exact amount if (_type == ActionType.SELL) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/SafeERC20.sol"; import "../../DS/DSMath.sol"; import "../../auth/AdminAuth.sol"; import "../DFSExchangeHelper.sol"; import "../../interfaces/OffchainWrapperInterface.sol"; import "../../interfaces/TokenInterface.sol"; contract ScpWrapper is OffchainWrapperInterface, DFSExchangeHelper, AdminAuth, DSMath { string public constant ERR_SRC_AMOUNT = "Not enough funds"; string public constant ERR_PROTOCOL_FEE = "Not enough eth for protcol fee"; string public constant ERR_TOKENS_SWAPED_ZERO = "Order success but amount 0"; using SafeERC20 for ERC20; /// @notice Takes order from Scp and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _type Action type (buy or sell) function takeOrder( ExchangeData memory _exData, ActionType _type ) override public payable returns (bool success, uint256) { // check that contract have enough balance for exchange and protocol fee require(getBalance(_exData.srcAddr) >= _exData.srcAmount, ERR_SRC_AMOUNT); require(getBalance(KYBER_ETH_ADDRESS) >= _exData.offchainData.protocolFee, ERR_PROTOCOL_FEE); ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { uint srcAmount = wdiv(_exData.destAmount, _exData.offchainData.price) + 1; // + 1 so we round up writeUint256(_exData.offchainData.callData, 36, srcAmount); } // we know that it will be eth if dest addr is either weth or eth address destAddr = _exData.destAddr == KYBER_ETH_ADDRESS ? EXCHANGE_WETH_ADDRESS : _exData.destAddr; uint256 tokensBefore = getBalance(destAddr); (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); uint256 tokensSwaped = 0; if (success) { // get the current balance of the swaped tokens tokensSwaped = getBalance(destAddr) - tokensBefore; require(tokensSwaped > 0, ERR_TOKENS_SWAPED_ZERO); } // returns all funds from src addr, dest addr and eth funds (protocol fee leftovers) sendLeftover(_exData.srcAddr, destAddr, msg.sender); return (success, tokensSwaped); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../utils/GasBurner.sol"; import "../../interfaces/ILendingPool.sol"; import "./CompoundSaverProxy.sol"; import "../../loggers/DefisaverLogger.sol"; import "../../auth/ProxyPermission.sol"; /// @title Entry point for the FL Repay Boosts, called by DSProxy contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x819879d4725944b679371cE64474d3B92253cAb6; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/ICompoundSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxyV2 is ProxyPermission { string public constant NAME = "AaveSubscriptionsProxyV2"; address public constant AAVE_SUBSCRIPTION_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD; address public constant AAVE_MONITOR_PROXY = 0x380982902872836ceC629171DaeAF42EcC02226e; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } pragma solidity ^0.6.0; import "../../auth/ProxyPermission.sol"; import "../../interfaces/IAaveSubscription.sol"; /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } pragma solidity ^0.6.0; import "../../DS/DSGuard.sol"; import "../../DS/DSAuth.sol"; contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } /// @title SubscriptionsProxy handles authorization and interaction with the Subscriptions contract contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x1816A86C4DA59395522a42b871bf11A4E96A1C7a; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } pragma solidity ^0.6.0; import "../../interfaces/OsmMom.sol"; import "../../interfaces/Osm.sol"; import "../../auth/AdminAuth.sol"; import "../../interfaces/Manager.sol"; contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } pragma solidity ^0.6.0; abstract contract OsmMom { mapping (bytes32 => address) public osms; } pragma solidity ^0.6.0; abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } pragma solidity ^0.6.0; import "./DSProxy.sol"; abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } pragma solidity ^0.6.0; import "./ERC20.sol"; //TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); }
Only monitor contract is able to call execute on users proxy _owner Address of cdp owner (users DSProxy address) _aaveSaverProxy Address of AaveSaverProxy _data Data to send to AaveSaverProxy execute reverts if calling specific method fails return if anything left
function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } }
381,276
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_763(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,476
./partial_match/4/0x0E69BcCfBC7D80457A6a7A6F12e0279bc964c518/sources/OneSplitAudit.sol
Calculate expected returning amount of `destToken` fromToken (IERC20) Address of token or `address(0)` for Ether destToken (IERC20) Address of token or `address(0)` for Ether amount (uint256) Amount for `fromToken` parts (uint256) Number of pieces source volume could be splitted, works like granularity, higly affects gas usage. Should be called offchain, but could be called onchain if user swaps not his own funds, but this is still considered as not safe. flags (uint256) Flags for enabling and disabling some features, default 0 destTokenEthPriceTimesGasPrice (uint256) destToken price to ETH multiplied by gas price
function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return oneSplitImpl.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); }
8,591,285
pragma solidity ^0.5.1; import '../AccessControl/AccessControl.sol'; import '../Core/Ownable.sol'; // Define a contract 'Supplychain' contract SupplyChain is AccessControl, Ownable { // Define a variable called 'NFTID' to identify the token used to manage to engineering intellectual property managed between the designer and the verifier uint NFTID; // Define a variable called 'FTI' for Fungible Token Inventory, the number of fungible tokens available to buy uint FTI; // Define a public mapping 'items' that maps the NFTID to a design item. mapping (uint => Item) items; // Define a public mapping 'itemsHistory' that maps the NFTID to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) itemsHistory; // Define enum 'State' with the following values: enum State { NFTMinted, NFTSentForVerification, NFTAwaitingVerification, NFTSentForVerification, NFTVerified, FTCreated, FTForSale, FTSold, FTMinted } // And a Material State enum enum MaterialState { NFT, // 1 FT // 2 } State constant defaultState = State.NFTMinted; DesignState constant defaultDesignState = MaterialState.NFT; // Define a struct 'Item' with the following fields: struct Item { uint FTI; // Fungible Token Inventory uint NFTID; // The Unique Identifer of the Engineering IP NFT from which the Fungible game items are minted address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through the stages address payable designerID; // Metamask-Ethereum address of the Designer string designerName; // Designer Name string designInformation; // Just a string for now, will likely be a tuple/list/dict type or link to IPFS uint FTPrice; // Price for the FT State itemState; // Product State as represented in the enum above MaterialState itemState2; // Material State of the product as represented by the enum above string productNotesByVerifier; // Product notes that are added by the Verifier address payable verifierID; // Metamask-Ethereum address of the Verifier address payable playerID; // Metamask-Ethereum address of the Player } // Define events with the same state values and accept 'upc' as input argument // event createNFT?? event NFTMinted (uint NFTID); event NFTSentForVerification (uint NFTID); event NFTAwaitingVerification (uint NFTID); event NFTVerificationRejected (uint NFTID); event NFTVerified (uint NFTID); event CreateFT (uint NFTID); event FTForSale (uint NFTID); event FTSold (uint NFTID); event FTMinted (uint NFTID); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _NFTID) { _; uint _price = items[_NFTID].productPrice; uint amountToReturn = msg.value - _price; items[_NFTID].ownerID.transfer(amountToReturn); } // Define a modifier that checks if an item.state of an NFTID is Minted modifier nftminded(uint _NFTID) { require(items[_NFTID].itemState == State.NFTMinted); _; } // Define a modifier that checks if an item.state of an NFTID is Awaiting Verification modifier nftsentforverification(uint _NFTID) { require(items[_upc].itemState == State.NFTSentForVerification); _; } // Define a modifier that checks if an item.state of an NFTID is Awaiting Verification modifier nftawaitingverification(uint _NFTID) { require(items[_NFTID].itemState == State.NFTAwaitingVerification); _; } // Define a modifier that checks if an item.state of an NFTID is Verified modifier nftverified(uint _NFTID) { require(items[_NFTID].itemState == State.NFTVerified); _; } // Define a modifier that checks if an item.state of a upc is ForSale modifier ftcreated(uint _NFTID) { require(items[_NFTID].itemState == State.FTCreated); _; } // Define a modifier that checks if an item.state of a upc is Sold modifier ftforsale(uint _NFTID) { require(items[_NFTID].itemState == State.FTForSale); _; } // Define a modifier that checks if an item.state of a upc is Shipped modifier ftsold(uint _NFTID) { require(items[_NFTID].itemState == State.FTSold); _; } // Define a modifier that checks if an item.state of a upc is Received modifier ftminted(uint _NFTID) { require(items[_NFTID].itemState == State.FTMinted); _; } // In the constructor // set 'FTInventory' to 0 // and set 'NFTID' to 1 constructor() public payable { FTInventory = 0; NFTID = 1; } // Define a function 'kill' if required function kill() public { if (msg.sender == owner()) { selfdestruct(msg.sender); } } // Define a function 'mintNFT' that allows a designer to mark an item 'NFTMinted' // Will need to be adjusted for production to emit an event that speaks to the Enjin Platform // Discuss with Witek function mintNFT(uint _NFTID, address _designerID, string memory _designerName, string memory _designInformation ) public verifyCaller(_designerID) //VerifyCaller onlyDesigner() // onlyHarvester() { // Require that the NFTID does not already exist (presumeably all NFT will have a unique ID when created, how to call it?) require(_NFTID != 0 && items[_NFTID].NFTID == 0, "This NFTID already exists."); // Add the new item as part of NFT creation (how can we integrate minting event with this, call directly from the token? Mint custom NFT?) Item memory newItem; newItem.NFTID = NFTID; newItem.ownerID = msg.sender; newItem.designerID = msg.sender; newItem.designerName = _designerName; newItem.designInformation = _designInformation; newItem.productNotes = _productNotes; newItem.itemState = State.NFTMinted; newItem.itemState2 = MaterialState.NFT; // Add item to mapping using UFC items[_NFTID] = newItem; // Emit the appropriate event (speak to Witek about what ti actually needs to look like) emit NFTMinted(_NFTMinted); } // Define a function 'sendForVerification' which is qualitatively similar to making an item available for sale // needs some kind of information sharing authorisation code function sendForVerification(uint _NFTID) public // Call modifier to check if NFTID has passed previous supply chain stage nftminted(_NFTID) // Only designer onlyDesigner() // Call modifier to verify caller of this function verifyCaller(items[_NFTID].designerID) { // Update the appropriate fields items[_NFTID].itemState = State.SentForVerification; // Emit the appropriate event emit SentForVerification(_NFTID); } // Define a function 'acceptForVerification' that allows a verifier to accept a design for verification // Qualitivately similar to buying an item function acceptForVerification(uint _NFTID) public // Call modifier to check if upc has passed previous supply chain stage nftsentforverification(_NFTID) // Only manufacturer onlyVerifier() // Call modifer to send any excess ether back to buyer verifyCaller(items[_NFTID].verifierID) { // Update the appropriate fields - ownerID, distributorID, itemState items[_NFTID].itemState = State.NFTAwaitingVerification; // emit the appropriate event emit NFTAwaitingVerification(_NFTID); } // Define a function 'rejectVerification' that allows a verifier to reject an engineering design function rejectVerification(uint _NFTID) public // Call modifier to check if upc has passed previous supply chain stage nftawaitingverification(_NFTID) // Only harvester onlyVerifier() // Call modifier to verify caller of this function verifyCaller(items[_NFTID].verifierID) { // Update the appropriate fields items[_NFTID].itemState = State.NFTMinted; // Emit the appropriate event emit NFTVerificationRejected(_NFTID); } // Define a function 'buyItem' that allows the disributor to mark an item 'Sold' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function verify(uint _NFTID) public // Call modifier to check if upc has passed previous supply chain stage awaitingverification(_NFTID) // Only manufacturer onlyVerifier() // Call modifer to send any excess ether back to buyer verifyCaller(items[_NFTID].verifierID) { // Update the appropriate fields - ownerID, distributorID, itemState items[_NFTID].itemState = State.NFTVerified; // emit the appropriate event emit NFTVerified(_NFTID); } // Define a function 'create' that allows the distributor to mark an item 'FTCreated' // Use the above modifers to check if the item is sold function createFT(uint _NFTID) public // Call modifier to check if upc has passed previous supply chain stage nftverified(_NFTID) // Only harvester onlyDesigner() // Call modifier to verify caller of this function verifyCaller(items[_NFTID].designerID) { // Update the appropriate fields (needs an asynchronous callback to enjin cloud somehow) items[_NFTID].itemState = State.FTCreated; // Emit the appropriate event emit CreateFT(_NFTID); // What is the callback sequence for this? Speak to Witek! } // Define a function 'ListForSale' that allows the manufacturer to mark an item 'FTListedForSale' // Use the above modifiers to check if the item is shipped function ListForSale(uint _NFTID, uint _price)) public // Call modifier to check if upc has passed previous supply chain stage ftcreated(_NFTID) // Only manufacturer onlyDesigner() // Access Control List enforced by calling Smart Contract / DApp verifyCaller(items[_NFTID].designerID) { // Update the appropriate fields items[_NFTID].productPrice = _price; items[_NFTID].itemState = State.FTForSale; // Emit the appropriate event emit FTForSale(_NFTID); } function buyFT(uint _NFTID) public payable // Call modifier to check if upc has passed previous supply chain stage FTForSale(_NFTID) // Only distributor onlyPlayer() // Call modifer to check if buyer has paid enough paidEnough(items[_NFTID].productPrice) // Call modifer to send any excess ether back to buyer checkValue(_NFT) { // Update the appropriate fields - ownerID, distributorID, itemState items[_NFTID].ownerID = msg.sender; items[_NFTID].playerID = msg.sender; items[_NFTID].itemState = State.FTSold; // Transfer money to farmer items[_NFTID].designerID.transfer(items[_NFTID].productPrice); // emit the appropriate event emit FTSold(_NFTID); } // Allow shipping of product by Manufacturer // Use the above modifers to check if the item is sold function MintFT(uint _NFTID) public // Call modifier to check if upc has passed previous supply chain stage FTSold(_NFTID) // Only manufacturer onlyDesigner() // Call modifier to verify caller of this function verifyCaller(items[_NFTID].designerID) { // Update the appropriate fields items[_NFTID].itemState = State.FTMinted; items[_NFTID].itemState2 = MaterialState.FT // Emit the appropriate event emit FTMinted(_NFTID); } // Work out parameters function fetchNFTBuffer(uint _NFTID) public view returns ( uint FTInventory, uint NFTID, address ownerID, address designerID, address verifierID, string memory designerName, string memory verifierName, string memory designInformation ) { // Assign values to the 8 parameters Item memory returnItem = items[_NFTID]; return ( returnItem.FTInventory, returnItem.NFTID, returnItem.designerID, returnItem.verifierID, returnItem.designerName, returnItem.verifierName, returnItem.designInformation ); } // Work out parameters function fetchFTBuffer(uint _upc) public view returns ( uint FTInventory, uint NFTID, address ownerID, address designerID, address verifierID, string memory designerName, string memory verifierName, string memory designInformation address payable playerID ) { // Assign values to the parameters Item memory returnItem = items[_NFTID]; return ( returnItem.FTInventory, returnItem.NFTID, returnItem.ownerID, returnItem.designerID, returnItem.verifierID, returnItem.designerName, returnItem.verifierName, returnItem.designInformation, returnItem.playerID ); } }
Define a function 'ListForSale' that allows the manufacturer to mark an item 'FTListedForSale' Use the above modifiers to check if the item is shipped Call modifier to check if upc has passed previous supply chain stage Only manufacturer Access Control List enforced by calling Smart Contract / DApp Update the appropriate fields Emit the appropriate event
function ListForSale(uint _NFTID, uint _price)) public ftcreated(_NFTID) onlyDesigner() verifyCaller(items[_NFTID].designerID) { items[_NFTID].productPrice = _price; items[_NFTID].itemState = State.FTForSale; emit FTForSale(_NFTID); }
1,021,442
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/EnumerableMap.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IBMIDAIStaking.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/IRewardsGenerator.sol"; import "./interfaces/ILiquidityMining.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IBMIStaking.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./tokens/ERC1155Upgradeable.sol"; import "./abstract/AbstractDependant.sol"; import "./abstract/AbstractSlasher.sol"; import "./Globals.sol"; contract BMIDAIStaking is IBMIDAIStaking, OwnableUpgradeable, ERC1155Upgradeable, AbstractDependant, AbstractSlasher { using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using SafeMath for uint256; using Math for uint256; IERC20 public daiToken; IERC20 public bmiToken; IPolicyBookRegistry public policyBookRegistry; IRewardsGenerator public rewardsGenerator; ILiquidityMining public liquidityMining; IBMIStaking public bmiStaking; ILiquidityRegistry public liquidityRegistry; mapping(uint256 => StakingInfo) internal _stakersPool; // nft index -> info uint256 internal _nftMintId; // next nft mint id mapping(address => EnumerableSet.UintSet) internal _nftHolderTokens; // holder -> nfts EnumerableMap.UintToAddressMap internal _nftTokenOwners; // index nft -> holder event StakingNFTMinted(uint256 id, address policyBookAddress, address to); event StakingNFTBurned(uint256 id, address policyBookAddress); event StakingBMIProfitWithdrawn( uint256 id, address policyBookAddress, address to, uint256 amount ); event StakingFundsWithdrawn(uint256 id, address policyBookAddress, address to, uint256 amount); event TokensRecovered(address to, uint256 amount); modifier onlyPolicyBooks() { require(policyBookRegistry.isPolicyBook(_msgSender()), "BDS: No access"); _; } function __BMIDAIStaking_init() external initializer { __Ownable_init(); __ERC1155_init(""); _nftMintId = 1; } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { daiToken = IERC20(_contractsRegistry.getDAIContract()); bmiToken = IERC20(_contractsRegistry.getBMIContract()); rewardsGenerator = IRewardsGenerator(_contractsRegistry.getRewardsGeneratorContract()); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); liquidityMining = ILiquidityMining(_contractsRegistry.getLiquidityMiningContract()); bmiStaking = IBMIStaking(_contractsRegistry.getBMIStakingContract()); liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); } /// @dev the output URI will be: "https://token-cdn-domain/<tokenId>" function uri(uint256 tokenId) public view override returns (string memory) { return string(abi.encodePacked(super.uri(0), Strings.toString(tokenId))); } /// @dev this is a correct URI: "https://token-cdn-domain/" function setBaseURI(string calldata newURI) external onlyOwner { _setURI(newURI); } function recoverTokens() external onlyOwner { uint256 balance = bmiToken.balanceOf(address(this)); bmiToken.transfer(_msgSender(), balance); emit TokensRecovered(_msgSender(), balance); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 1) { // not an NFT continue; } if (from == address(0)) { // mint happened _nftHolderTokens[to].add(ids[i]); _nftTokenOwners.set(ids[i], to); } else if (to == address(0)) { // burn happened _nftHolderTokens[from].remove(ids[i]); _nftTokenOwners.remove(ids[i]); } else { // transfer happened _nftHolderTokens[from].remove(ids[i]); _nftHolderTokens[to].add(ids[i]); _nftTokenOwners.set(ids[i], to); _updateLiquidityRegistry(to, from, _stakersPool[ids[i]].policyBookAddress); } } } function _updateLiquidityRegistry( address to, address from, address policyBookAddress ) internal { liquidityRegistry.tryToAddPolicyBook(to, policyBookAddress); liquidityRegistry.tryToRemovePolicyBook(from, policyBookAddress); } function _mintStake(address staker, uint256 id) internal { _mint(staker, id, 1, ""); // mint NFT } function _burnStake(address staker, uint256 id) internal { _burn(staker, id, 1); // burn NFT } function _mintAggregatedNFT( address staker, address policyBookAddress, uint256[] memory tokenIds ) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 totalBmiDaiAmount; for (uint256 i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == _msgSender(), "BDS: Not a token owner"); require( _stakersPool[tokenIds[i]].policyBookAddress == policyBookAddress, "BDS: NFTs from distinct origins" ); totalBmiDaiAmount = totalBmiDaiAmount.add( _stakersPool[tokenIds[i]].stakedBmiDaiAmount ); _burnStake(staker, tokenIds[i]); emit StakingNFTBurned(tokenIds[i], policyBookAddress); /// @dev should be enough delete _stakersPool[tokenIds[i]].policyBookAddress; } _mintStake(staker, _nftMintId); _stakersPool[_nftMintId] = StakingInfo(policyBookAddress, totalBmiDaiAmount); emit StakingNFTMinted(_nftMintId, policyBookAddress, staker); _nftMintId++; } function _mintNewNFT( address staker, uint256 bmiDaiAmount, address policyBookAddress ) internal { _mintStake(staker, _nftMintId); _stakersPool[_nftMintId] = StakingInfo(policyBookAddress, bmiDaiAmount); emit StakingNFTMinted(_nftMintId, policyBookAddress, staker); _nftMintId++; } function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external override { require(tokenIds.length > 1, "BDS: Can't aggregate"); _mintAggregatedNFT(_msgSender(), policyBookAddress, tokenIds); rewardsGenerator.aggregate(policyBookAddress, tokenIds, _nftMintId - 1); // nftMintId is changed, so -1 } function stakeDAIx(uint256 bmiDaiAmount, address policyBookAddress) external override { _stakeDAIx(_msgSender(), bmiDaiAmount, policyBookAddress); } function stakeDAIxWithPermit( uint256 bmiDaiAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) external override { _stakeDAIxWithPermit(_msgSender(), bmiDaiAmount, policyBookAddress, v, r, s); } function stakeDAIxFrom(address user, uint256 bmiDaiAmount) external override onlyPolicyBooks { _stakeDAIx(user, bmiDaiAmount, _msgSender()); } function stakeDAIxFromWithPermit( address user, uint256 bmiDaiAmount, uint8 v, bytes32 r, bytes32 s ) external override onlyPolicyBooks { _stakeDAIxWithPermit(user, bmiDaiAmount, _msgSender(), v, r, s); } function _stakeDAIxWithPermit( address staker, uint256 bmiDaiAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) internal { IERC20PermitUpgradeable(policyBookAddress).permit( staker, address(this), bmiDaiAmount, MAX_INT, v, r, s ); _stakeDAIx(staker, bmiDaiAmount, policyBookAddress); } function _stakeDAIx( address user, uint256 bmiDaiAmount, address policyBookAddress ) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); require(IPolicyBook(policyBookAddress).whitelisted(), "BDS: PB is not whitelisted"); require(bmiDaiAmount > 0, "BDS: Zero tokens"); uint256 daiAmount = IPolicyBook(policyBookAddress).convertDAIXToDAI(bmiDaiAmount); // transfer bmiDAIx from user to staking IERC20(policyBookAddress).transferFrom(user, address(this), bmiDaiAmount); _mintNewNFT(user, bmiDaiAmount, policyBookAddress); rewardsGenerator.stake(policyBookAddress, _nftMintId - 1, daiAmount); // nftMintId is changed, so -1 } function _transferProfit(uint256 tokenId, bool onlyProfit) internal { address policyBookAddress = _stakersPool[tokenId].policyBookAddress; uint256 totalProfit; if (onlyProfit) { totalProfit = rewardsGenerator.withdrawReward(policyBookAddress, tokenId); } else { totalProfit = rewardsGenerator.withdrawFunds(policyBookAddress, tokenId); } uint256 bmiStakingProfit = _getSlashed(totalProfit, liquidityMining.startLiquidityMiningTime()); uint256 profit = totalProfit.sub(bmiStakingProfit); // transfer slashed bmi to the bmiStaking and add them to the pool bmiToken.transfer(address(bmiStaking), bmiStakingProfit); bmiStaking.addToPool(bmiStakingProfit); // transfer bmi profit to the user bmiToken.transfer(_msgSender(), profit); emit StakingBMIProfitWithdrawn(tokenId, policyBookAddress, _msgSender(), profit); } function getPolicyBookAPY(address policyBookAddress) public view override returns (uint256) { return IPolicyBook(policyBookAddress).whitelisted() ? rewardsGenerator.getPolicyBookAPY(policyBookAddress) : 0; } function _aggregateForEach( address staker, address policyBookAddress, uint256 offset, uint256 limit, function(uint256) view returns (uint256) func ) internal view returns (uint256 total) { bool nullAddr = policyBookAddress == address(0); require(nullAddr || policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 to = (offset.add(limit)).min(balanceOf(staker)).max(offset); for (uint256 i = offset; i < to; i++) { uint256 nftIndex = tokenOfOwnerByIndex(staker, i); if (nullAddr || _stakersPool[nftIndex].policyBookAddress == policyBookAddress) { total = total.add(func(nftIndex)); } } } function _transferForEach(address policyBookAddress, function(uint256) func) internal { require(policyBookRegistry.isPolicyBook(policyBookAddress), "BDS: Not a PB"); uint256 stakerBalance = balanceOf(_msgSender()); for (int256 i = int256(stakerBalance) - 1; i >= 0; i--) { uint256 nftIndex = tokenOfOwnerByIndex(_msgSender(), uint256(i)); if (_stakersPool[nftIndex].policyBookAddress == policyBookAddress) { func(nftIndex); } } } function restakeBMIProfit(uint256 tokenId) public override { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); uint256 totalProfit = rewardsGenerator.withdrawReward(_stakersPool[tokenId].policyBookAddress, tokenId); bmiToken.transfer(address(bmiStaking), totalProfit); bmiStaking.stakeFor(_msgSender(), totalProfit); } function restakeStakerBMIProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, restakeBMIProfit); } function withdrawBMIProfit(uint256 tokenId) public override { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); _transferProfit(tokenId, true); } function withdrawStakerBMIProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, withdrawBMIProfit); } function withdrawFundsWithProfit(uint256 tokenId) public override { address policyBookAddress = _stakersPool[tokenId].policyBookAddress; require(policyBookAddress != address(0), "BDS: Token doesn't exist"); require(ownerOf(tokenId) == _msgSender(), "BDS: Not a token owner"); _transferProfit(tokenId, false); uint256 stakedFunds = _stakersPool[tokenId].stakedBmiDaiAmount; // transfer bmiDAIx from staking to the user IERC20(policyBookAddress).transfer(_msgSender(), stakedFunds); emit StakingFundsWithdrawn(tokenId, policyBookAddress, _msgSender(), stakedFunds); _burnStake(_msgSender(), tokenId); emit StakingNFTBurned(tokenId, policyBookAddress); delete _stakersPool[tokenId]; } function withdrawStakerFundsWithProfit(address policyBookAddress) external override { _transferForEach(policyBookAddress, withdrawFundsWithProfit); } function stakingInfoByToken(uint256 tokenId) external view override returns (StakingInfo memory) { require(_stakersPool[tokenId].policyBookAddress != address(0), "BDS: Token doesn't exist"); return _stakersPool[tokenId]; } /// @notice should be used regarding balanceOf() function /// @dev offset and limit is taken in regards of NFTs on account function stakingInfoByStaker( address staker, address[] calldata policyBooksAddresses, uint256 offset, uint256 limit ) external view override returns ( PolicyBookInfo[] memory policyBooksInfo, UserInfo[] memory usersInfo, uint256[] memory nftsCount, NFTsInfo[][] memory nftsInfo ) { uint256 to = (offset.add(limit)).min(balanceOf(staker)).max(offset); policyBooksInfo = new PolicyBookInfo[](policyBooksAddresses.length); usersInfo = new UserInfo[](policyBooksAddresses.length); nftsCount = new uint256[](policyBooksAddresses.length); nftsInfo = new NFTsInfo[][](policyBooksAddresses.length); for (uint256 i = 0; i < policyBooksAddresses.length; i++) { nftsInfo[i] = new NFTsInfo[](to - offset); policyBooksInfo[i] = PolicyBookInfo( rewardsGenerator.getStakedPolicyBookDAI(policyBooksAddresses[i]), rewardsGenerator.getPolicyBookRewardPerBlock(policyBooksAddresses[i]), getPolicyBookAPY(policyBooksAddresses[i]), IPolicyBook(policyBooksAddresses[i]).getAPY() ); for (uint256 j = offset; j < to; j++) { uint256 nftIndex = tokenOfOwnerByIndex(staker, j); if (_stakersPool[nftIndex].policyBookAddress == policyBooksAddresses[i]) { nftsInfo[i][nftsCount[i]] = NFTsInfo( nftIndex, uri(nftIndex), _stakersPool[nftIndex].stakedBmiDaiAmount, rewardsGenerator.getStakedNFTDAI(nftIndex), getBMIProfit(nftIndex) ); usersInfo[i].totalStakedBmiDai = usersInfo[i].totalStakedBmiDai.add( nftsInfo[i][nftsCount[i]].stakedBmiDaiAmount ); usersInfo[i].totalStakedDai = usersInfo[i].totalStakedDai.add( nftsInfo[i][nftsCount[i]].stakedDaiAmount ); usersInfo[i].totalBmiReward = usersInfo[i].totalBmiReward.add( nftsInfo[i][nftsCount[i]].reward ); nftsCount[i]++; } } } } /// @dev returns percentage multiplied by 10**25 function getSlashingPercentage() external view override returns (uint256) { return getSlashingPercentage(liquidityMining.startLiquidityMiningTime()); } function getSlashedBMIProfit(uint256 tokenId) public view override returns (uint256) { return _applySlashing(getBMIProfit(tokenId), liquidityMining.startLiquidityMiningTime()); } function getBMIProfit(uint256 tokenId) public view override returns (uint256) { return rewardsGenerator.getReward(_stakersPool[tokenId].policyBookAddress, tokenId); } function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view override returns (uint256 totalProfit) { uint256 stakerBMIProfit = getStakerBMIProfit(staker, policyBookAddress, offset, limit); return _applySlashing(stakerBMIProfit, liquidityMining.startLiquidityMiningTime()); } function getStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) public view override returns (uint256) { return _aggregateForEach(staker, policyBookAddress, offset, limit, getBMIProfit); } function totalStaked(address user) external view override returns (uint256) { return _aggregateForEach(user, address(0), 0, MAX_INT, stakedByNFT); } function totalStakedDAI(address user) external view override returns (uint256) { return _aggregateForEach(user, address(0), 0, MAX_INT, stakedDAIByNFT); } function stakedByNFT(uint256 tokenId) public view override returns (uint256) { return _stakersPool[tokenId].stakedBmiDaiAmount; } function stakedDAIByNFT(uint256 tokenId) public view override returns (uint256) { return rewardsGenerator.getStakedNFTDAI(tokenId); } function policyBookByNFT(uint256 tokenId) external view override returns (address) { return _stakersPool[tokenId].policyBookAddress; } /// @notice returns number of NFTs on user's account function balanceOf(address user) public view override returns (uint256) { return _nftHolderTokens[user].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _nftTokenOwners.get(tokenId); } function tokenOfOwnerByIndex(address user, uint256 index) public view override returns (uint256) { return _nftHolderTokens[user].at(index); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS; // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "../Globals.sol"; abstract contract AbstractSlasher { using SafeMath for uint256; using Math for uint256; uint256 public constant MAX_EXIT_FEE = 90 * PRECISION; uint256 public constant MIN_EXIT_FEE = 20 * PRECISION; uint256 public constant EXIT_FEE_DURATION = 100 days; function getSlashingPercentage(uint256 startTime) public view returns (uint256) { startTime = startTime == 0 || startTime > block.timestamp ? block.timestamp : startTime; uint256 feeSpan = MAX_EXIT_FEE.sub(MIN_EXIT_FEE); uint256 feePerSecond = feeSpan.div(EXIT_FEE_DURATION); uint256 fee = Math.min(block.timestamp.sub(startTime).mul(feePerSecond), feeSpan); return MAX_EXIT_FEE.sub(fee); } function getSlashingPercentage() external view virtual returns (uint256); function _applySlashing(uint256 amount, uint256 startTime) internal view returns (uint256) { return amount.sub(_getSlashed(amount, startTime)); } function _getSlashed(uint256 amount, uint256 startTime) internal view returns (uint256) { return amount.mul(getSlashingPercentage(startTime)).div(PERCENTAGE_100); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IBMIDAIStaking { struct StakingInfo { address policyBookAddress; uint256 stakedBmiDaiAmount; } struct PolicyBookInfo { uint256 totalStakedDai; uint256 rewardPerBlock; uint256 stakingAPY; uint256 liquidityAPY; } struct UserInfo { uint256 totalStakedBmiDai; uint256 totalStakedDai; uint256 totalBmiReward; } struct NFTsInfo { uint256 nftIndex; string uri; uint256 stakedBmiDaiAmount; uint256 stakedDaiAmount; uint256 reward; } function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external; function stakeDAIx(uint256 amount, address policyBookAddress) external; function stakeDAIxWithPermit( uint256 bmiDaiAmount, address policyBookAddress, uint8 v, bytes32 r, bytes32 s ) external; function stakeDAIxFrom(address user, uint256 amount) external; function stakeDAIxFromWithPermit( address user, uint256 bmiDaiAmount, uint8 v, bytes32 r, bytes32 s ) external; function getPolicyBookAPY(address policyBookAddress) external view returns (uint256); function restakeBMIProfit(uint256 tokenId) external; function restakeStakerBMIProfit(address policyBookAddress) external; function withdrawBMIProfit(uint256 tokenID) external; function withdrawStakerBMIProfit(address policyBookAddress) external; function withdrawFundsWithProfit(uint256 tokenID) external; function withdrawStakerFundsWithProfit(address policyBookAddress) external; function stakingInfoByToken(uint256 tokenID) external view returns (StakingInfo memory); /// @notice exhaustive information about staker's stakes /// @param staker is a user to return information for /// @param policyBooksAddresses is an array of PolicyBooks to check the stakes in /// @param offset is a starting ordinal number of user's NFT /// @param limit is a number of NFTs to check per function's call /// @return policyBooksInfo - an array of infos (totalStakedDai, rewardPerBlock (in BMI), stakingAPY, liquidityAPY) /// @return usersInfo - an array of user's info per PolicyBook (totalStakedBmiDai, totalStakedDai, totalBmiReward) /// @return nftsCount - number of NFTs for each respective PolicyBook /// @return nftsInfo - 2 dimensional array of NFTs info per each PolicyBook (nftIndex, uri, stakedBmiDaiAmount, stakedDaiAmount, reward (in BMI)) function stakingInfoByStaker( address staker, address[] calldata policyBooksAddresses, uint256 offset, uint256 limit ) external view returns ( PolicyBookInfo[] memory policyBooksInfo, UserInfo[] memory usersInfo, uint256[] memory nftsCount, NFTsInfo[][] memory nftsInfo ); function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256); function getBMIProfit(uint256 tokenId) external view returns (uint256); function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view returns (uint256 totalProfit); function getStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit ) external view returns (uint256 totalProfit); function totalStaked(address user) external view returns (uint256); function totalStakedDAI(address user) external view returns (uint256); function stakedByNFT(uint256 tokenId) external view returns (uint256); function stakedDAIByNFT(uint256 tokenId) external view returns (uint256); function policyBookByNFT(uint256 tokenId) external view returns (address); function balanceOf(address user) external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address); function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./tokens/ISTKBMIToken.sol"; interface IBMIStaking { event StakedBMI(uint256 stakedBMI, uint256 mintedStkBMI, address indexed recipient); event BMIWithdrawn(uint256 amountBMI, uint256 burnedStkBMI, address indexed recipient); event UnusedRewardPoolRevoked(address recipient, uint256 amount); struct WithdrawalInfo { uint256 coolDownTimeEnd; uint256 amountBMIRequested; } function stakeWithPermit( uint256 _amountBMI, uint8 _v, bytes32 _r, bytes32 _s ) external; function stakeFor(address _user, uint256 _amountBMI) external; function stake(uint256 _amountBMI) external; function maturityAt() external view returns (uint256); function isBMIRewardUnlocked() external view returns (bool); function whenCanWithdrawBMIReward(address _address) external view returns (uint256); function unlockTokensToWithdraw(uint256 _amountBMIUnlock) external; function withdraw() external; /// @notice Getting withdraw information /// @return _amountBMIRequested is amount of bmi tokens requested to unlock /// @return _amountStkBMI is amount of stkBMI that will burn /// @return _unlockPeriod is its timestamp when user can withdraw /// returns 0 if it didn't unlocked yet. User has 48hs to withdraw /// @return _availableFor is the end date if withdraw period has already begun /// or 0 if it is expired or didn't start function getWithdrawalInfo(address _userAddr) external view returns ( uint256 _amountBMIRequested, uint256 _amountStkBMI, uint256 _unlockPeriod, uint256 _availableFor ); function addToPool(uint256 _amount) external; function stakingReward(uint256 _amount) external view returns (uint256); function getStakedBMI(address _address) external view returns (uint256); function getAPY() external view returns (uint256); function setRewardPerBlock(uint256 _amount) external; function revokeUnusedRewardPool() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getWETHContract() external view returns (address); function getDAIContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMIDAIStakingContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingContract() external view returns (address); function getReputationSystemContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityMining { struct TeamDetails { string teamName; address referralLink; uint256 membersNumber; uint256 totalStakedAmount; uint256 totalReward; } struct UserInfo { address userAddr; string teamName; uint256 stakedAmount; uint256 mainNFT; // 0 or NFT index if available uint256 platinumNFT; // 0 or NFT index if available } struct UserRewardsInfo { string teamName; uint256 totalBMIReward; // total BMI reward uint256 availableBMIReward; // current claimable BMI reward uint256 incomingPeriods; // how many month are incoming uint256 timeToNextDistribution; // exact time left to next distribution uint256 claimedBMI; // actual number of claimed BMI uint256 mainNFTAvailability; // 0 or NFT index if available uint256 platinumNFTAvailability; // 0 or NFT index if available bool claimedNFTs; // true if user claimed NFTs } struct MyTeamInfo { TeamDetails teamDetails; uint256 myStakedAmount; uint256 teamPlace; } struct UserTeamInfo { address teamAddr; uint256 stakedAmount; uint256 countOfRewardedMonth; bool isNFTDistributed; } struct TeamInfo { string name; uint256 totalAmount; address[] teamLeaders; } function startLiquidityMiningTime() external view returns (uint256); function getTopTeams() external view returns (TeamDetails[] memory teams); function getTopUsers() external view returns (UserInfo[] memory users); function getAllTeamsLength() external view returns (uint256); function getAllTeamsDetails(uint256 _offset, uint256 _limit) external view returns (TeamDetails[] memory _teamDetailsArr); function getMyTeamsLength() external view returns (uint256); function getMyTeamMembers(uint256 _offset, uint256 _limit) external view returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount); function getAllUsersLength() external view returns (uint256); function getAllUsersInfo(uint256 _offset, uint256 _limit) external view returns (UserInfo[] memory _userInfos); function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo); function getRewardsInfo(address user) external view returns (UserRewardsInfo memory userRewardInfo); function createTeam(string calldata _teamName) external; function deleteTeam() external; function joinTheTeam(address _referralLink) external; function getSlashingPercentage() external view returns (uint256); function investDAI(uint256 _tokensAmount, address _policyBookAddr) external; function distributeNFT() external; function checkPlatinumNFTReward(address _userAddr) external view returns (uint256); function checkMainNFTReward(address _userAddr) external view returns (uint256); function distributeBMIReward() external; function getTotalUserBMIReward(address _userAddr) external view returns (uint256); function checkAvailableBMIReward(address _userAddr) external view returns (uint256); /// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called) /// @return true if LM is started and not ended, false otherwise function isLMLasting() external view returns (bool); /// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started /// @return true if LM is finished, false if event is still going or not started function isLMEnded() external view returns (bool); function getEndLMTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityRegistry { struct LiquidityInfo { address policyBookAddr; uint256 lockedAmount; uint256 availableAmount; uint256 bmiDaiRatio; // multiply availableAmount by this num to get DAI } struct WithdrawalRequestInfo { address policyBookAddr; uint256 requestAmount; uint256 requestDAIAmount; uint256 availableLiquidity; uint256 readyToWithdrawDate; uint256 endWithdrawDate; } struct WithdrawalSetInfo { address policyBookAddr; uint256 requestAmount; uint256 requestDAIAmount; uint256 availableDAIAmount; } function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external; function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external; function getPolicyBooksArrLength(address _userAddr) external view returns (uint256); function getPolicyBooksArr(address _userAddr) external view returns (address[] memory _resultArr); function getLiquidityInfos( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (LiquidityInfo[] memory _resultArr); function getWithdrawalRequests( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr); function getWithdrawalSet( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } function EPOCH_DURATION() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get DAI equivalent function convertDAIXToDAI(uint256 _amount) external view returns (uint256); /// @notice get DAIx equivalent function convertDAIToDAIX(uint256 _amount) external view returns (uint256); /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price function getPolicyPrice(uint256 _epochsNumber, uint256 _coverTokens) external view returns (uint256 totalSeconds, uint256 totalPrice); function buyPolicyFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens ) external; /// @notice Let user to buy policy by supplying DAI, access: ANY /// @param _durationSeconds is number of seconds to cover /// @param _coverTokens is number of tokens to cover function buyPolicy(uint256 _durationSeconds, uint256 _coverTokens) external; function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let user to add liquidity by supplying DAI, access: ANY /// @param _liqudityAmount is amount of DAI tokens to secure function addLiquidity(uint256 _liqudityAmount) external; /// @notice Let eligible contracts add liqiudity for another user by supplying DAI /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of DAI tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _bmiDAIxAmount) external; function getAvailableDAIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw) external; function requestWithdrawalWithPermit( uint256 _tokensToWithdraw, uint8 _v, bytes32 _r, bytes32 _s ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalDaiLiquidity is PolicyBook's liquidity /// @return _stakedDAI is how much DAI are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalDaiLiquidity, uint256 _stakedDAI, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiDaiRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiDaiX) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiDAIx token desription for this policy book /// @param _projectSymbol replaces x in bmiDAIx token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalDaiLiquidity; uint256 stakedDAI; uint256 APY; uint256 annualInsuranceCost; uint256 bmiDaiRatio; bool whitelisted; } /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IRewardsGenerator { struct PolicyBookRewardInfo { uint256 rewardMultiplier; // includes 5 decimal places uint256 totalStaked; uint256 startStakeBlock; uint256 lastUpdateBlock; uint256 cumulativeSum; // includes 100 percentage uint256 cumulativeReward; uint256 average; // includes 100 percentage uint256 toUpdateAverage; // includes 100 percentage } struct StakeRewardInfo { uint256 averageOnStake; // includes 100 percentage uint256 aggregatedReward; uint256 stakeAmount; uint256 stakeBlock; } /// @notice this function is called every time policybook's DAI to DAIx rate changes function updatePolicyBookShare(uint256 newRewardMultiplier) external; /// @notice aggregates specified nfts into a single one function aggregate( address policyBookAddress, uint256[] calldata nftIndexes, uint256 nftIndexTo ) external; /// @notice informs generator of stake (rewards) function stake( address policyBookAddress, uint256 nftIndex, uint256 amount ) external; /// @notice returns policybook's APY multiplied by 10**5 function getPolicyBookAPY(address policyBookAddress) external view returns (uint256); /// @dev returns PolicyBook reward per block multiplied by 10**25 function getPolicyBookRewardPerBlock(address policyBookAddress) external view returns (uint256); /// @notice returns PolicyBook's staked DAI function getStakedPolicyBookDAI(address policyBookAddress) external view returns (uint256); /// @notice returns NFT's staked DAI function getStakedNFTDAI(uint256 nftIndex) external view returns (uint256); /// @notice returns a reward of NFT function getReward(address policyBookAddress, uint256 nftIndex) external view returns (uint256); /// @notice informs generator of withdrawal (all funds) function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256); /// @notice informs generator of withdrawal (rewards) function withdrawReward(address policyBookAddress, uint256 nftIndex) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ISTKBMIToken is IERC20Upgradeable { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155MetadataURIUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { require(account != address(0), "ERC1155: zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: self approval"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer failed" ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: length mismatch"); require(to != address(0), "ERC1155: zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer failed" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance"); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: zero address"); address operator = _msgSender(); _beforeTokenTransfer( operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: zero address"); require(ids.length == amounts.length, "ERC1155: length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer( operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "" ); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: non ERC1155Receiver"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: non ERC1155Receiver"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @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; } } // SPDX-License-Identifier: 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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // 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 Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_burn}. Requirements: - `ids` and `amounts` must have the same length./
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); }
1,302,286
./full_match/97/0xa123c510802A8c6A37a1db5F1e6e78e67439ba9f/sources/project_/contracts/piMarket.sol
BidOrder[] memory bids = Bids[_tokenId];
function withdrawBidMoney( uint256 _saleId, uint256 _bidId ) external nonReentrant { require(msg.sender != _tokenMeta[_saleId].currentOwner); BidOrder memory bids = Bids[_saleId][_bidId]; require(_tokenMeta[_saleId].price != bids.price); require(bids.buyerAddress == msg.sender); require(!bids.withdrawn); if (success) { Bids[_saleId][_bidId].withdrawn = true; revert("No Money left!"); } emit BidWithdrawn(_saleId, _bidId); }
3,291,748
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // File: @chainlink/contracts/src/v0.8/dev/VRFRequestIDBase.sol pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: @chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts/OwnershipAgreementv3.sol pragma solidity >=0.7.0 <0.9.0; /// @title Creates an Ownership Agreement, with an optional Operator role /// @author Dr. Jonathan Shahen at UREEQA /// @notice TODO /// @dev Maximum number of Owners is set to 255 (unit8.MAX_VALUE) contract OwnershipAgreementv3 { /* * Storage */ // ResolutionTypes: uint constant private resTypeNone = 0; // This indicates that the resolution hasn't been set (default value) uint constant private resTypeAddOwner = 1; uint constant private resTypeRemoveOwner = 2; uint constant private resTypeReplaceOwner = 3; uint constant private resTypeAddOperator = 4; uint constant private resTypeRemoveOperator = 5; uint constant private resTypeReplaceOperator = 6; uint constant private resTypeUpdateThreshold = 7; uint constant private resTypeUpdateTransactionLimit = 8; uint constant private resTypePause = 9; uint constant private resTypeUnpause = 10; uint constant private resTypeCustom = 1000; // Custom resoutions for each subclass struct Resolution { // Has the resolution already been passed bool passed; // The type of resolution uint256 resType; // The old address, can be address(0). oldAddress and newAddress cannot both equal address(0). address oldAddress; // The new address, can be address(0). oldAddress and newAddress cannot both equal address(0). address newAddress; // Able to store extra information for custom resolutions bytes32[] extra; } using EnumerableSet for EnumerableSet.AddressSet; // Set of owners // NOTE: we utilize a set, so we can enumerate the owners and so that the list only contains one instance of an account // NOTE: address(0) is not a valid owner EnumerableSet.AddressSet private _owners; // Value to indicate if the smart contract is paused bool private _paused; // An address, usually controlled by a computer, that performs regular/automated operations within the smart contract // NOTE: address(0) is not a valid operator EnumerableSet.AddressSet private _operators; // Limit the number of operators uint256 public operatorLimit = 1; // The number of owners it takes to come to an agreement uint256 public ownerAgreementThreshold = 1; // Limit per Transaction to impose // A limit of zero means no limit imposed uint256 public transactionLimit = 0; // Stores each vote for each resolution number (int) mapping(address => mapping(uint256 => bool)) public ownerVotes; // The next available resolution number uint256 public nextResolution = 1; mapping(address => uint256) lastOwnerResolutionNumber; // Stores the resolutions mapping(uint256 => Resolution) public resolutions; // //////////////////////////////////////////////////// // EVENTS // //////////////////////////////////////////////////// event OwnerAddition(address owner); event OwnerRemoval(address owner); event OwnerReplacement(address oldOwner, address newOwner); event OperatorAddition(address newOperator); event OperatorRemoval(address oldOperator); event OperatorReplacement(address oldOperator, address newOperator); event UpdateThreshold(uint256 newThreshold); event UpdateNumberOfOperators(uint256 newOperators); event UpdateTransactionLimit(uint256 newLimit); /// @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); // //////////////////////////////////////////////////// // MODIFIERS // //////////////////////////////////////////////////// function isValidAddress(address newAddr) public pure { require(newAddr != address(0), "Invaild Address"); } modifier onlyOperators() { isValidAddress(msg.sender); require( EnumerableSet.contains(_operators, msg.sender) == true, "Only the operator can run this function." ); _; } modifier onlyOwners() { isValidAddress(msg.sender); require( EnumerableSet.contains(_owners, msg.sender) == true, "Only an owner can run this function." ); _; } modifier onlyOwnersOrOperator() { isValidAddress(msg.sender); require( EnumerableSet.contains(_operators, msg.sender) == true || EnumerableSet.contains(_owners, msg.sender) == true, "Only an owner or the operator can run this function." ); _; } modifier ownerExists(address thisOwner) { require( EnumerableSet.contains(_owners, thisOwner) == true, "Owner does not exists." ); _; } /** * @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, "Smart Contract is paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * Requirements: The contract must be paused. */ modifier whenPaused() { require(_paused, "Smart Contract is not paused"); _; } /// @dev Modifier to make a function callable only when the amount is within the transaction limit modifier withinLimit(uint256 amount) { require( transactionLimit == 0 || amount <= transactionLimit, "Amount is over the transaction limit" ); _; } // //////////////////////////////////////////////////// // CONSTRUCTOR // //////////////////////////////////////////////////// constructor() { _addOwner(msg.sender); _paused = false; } // //////////////////////////////////////////////////// // VIEW FUNCTIONS // //////////////////////////////////////////////////// /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { if(EnumerableSet.length(_owners) == 0) return address(0); return EnumerableSet.at(_owners, 0); } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { uint256 len = EnumerableSet.length(_owners); address[] memory o = new address[](len); for (uint256 i = 0; i < len; i++) { o[i] = EnumerableSet.at(_owners, i); } return o; } /// @dev Returns the number of owners. /// @return Number of owners. function getNumberOfOwners() public view returns (uint) { return EnumerableSet.length(_owners); } /// @dev Returns list of owners. /// @return List of owner addresses. function getOperators() public view returns (address[] memory) { uint256 len = EnumerableSet.length(_operators); address[] memory o = new address[](len); for (uint256 i = 0; i < len; i++) { o[i] = EnumerableSet.at(_operators, i); } return o; } /// @dev Returns the number of operators. /// @return Number of operators. function getNumberOfOperators() public view returns (uint8) { return uint8(EnumerableSet.length(_operators)); } /// @dev How many owners does it take to approve a resolution /// @return minimum number of owner votes function getVoteThreshold() public view returns (uint256) { return ownerAgreementThreshold; } /// @dev Returns the maximum amount a transaction can contain /// @return maximum amount or zero is no limit function getTransactionLimit() public view returns (uint256) { return transactionLimit; } /// @dev Returns the next available resolution. /// @return The next available resolution number function getNextResolutionNumber() public view returns (uint256) { return nextResolution; } /// @dev Returns the next available resolution. /// @return The next available resolution number function getLastOwnerResolutionNumber(address thisOwner) public view returns (uint256) { return lastOwnerResolutionNumber[thisOwner]; } /// @dev Returns true if the contract is paused, and false otherwise. function paused() public view returns (bool) { return _paused; } /// @dev Helper function to fail if resolution number is already in use. function resolutionAlreadyUsed(uint256 resNum) public view { require( // atleast one of the address must not be equal to address(0) !(resolutions[resNum].oldAddress != address(0) || resolutions[resNum].newAddress != address(0)), "Resolution is already in use." ); } function isResolutionPassed(uint256 resNum) public view returns (bool) { return resolutions[resNum].passed; } function canResolutionPass(uint256 resNum) public view returns (bool) { uint256 voteCount = 0; uint256 len = EnumerableSet.length(_owners); for (uint256 i = 0; i < len; i++) { if (ownerVotes[EnumerableSet.at(_owners, i)][resNum] == true) { voteCount++; } } return voteCount >= ownerAgreementThreshold; } // //////////////////////////////////////////////////// // PUBLIC FUNCTIONS // //////////////////////////////////////////////////// /// @notice Vote Yes on a Resolution. /// @dev The owner who tips the agreement threshold will pay the gas for performing the resolution. /// @return TRUE if the resolution passed function voteResolution(uint256 resNum) public onlyOwners() returns (bool) { ownerVotes[msg.sender][resNum] = true; // If the reolution has already passed, then do nothing if (isResolutionPassed(resNum)) { return true; } // If the resolution can now be passed, then do so if (canResolutionPass(resNum)) { _performResolution(resNum); return true; } // The resolution cannot be passed yet return false; } /// @dev Create a resolution to add an owner. Performs addition if threshold is 1 or zero. function createResolutionAddOwner(address newOwner) public onlyOwners() { isValidAddress(newOwner); require( !EnumerableSet.contains(_owners, newOwner), "newOwner already exists." ); createResolution(resTypeAddOwner, address(0), newOwner, new bytes32[](0)); } /// @dev Create a resolution to remove an owner. Performs removal if threshold is 1 or zero. /// @dev Updates the threshold to keep it less than or equal to the number of new owners function createResolutionRemoveOwner(address oldOwner) public onlyOwners() { isValidAddress(oldOwner); require(getNumberOfOwners() > 1, "Must always be one owner"); require( EnumerableSet.contains(_owners, oldOwner), "owner is not an owner." ); createResolution(resTypeRemoveOwner, oldOwner, address(0), new bytes32[](0)); } /// @dev Create a resolution to repalce an owner. Performs replacement if threshold is 1 or zero. function createResolutionReplaceOwner(address oldOwner, address newOwner) public onlyOwners() { isValidAddress(oldOwner); isValidAddress(newOwner); require( EnumerableSet.contains(_owners, oldOwner), "oldOwner is not an owner." ); require( !EnumerableSet.contains(_owners, newOwner), "newOwner already exists." ); createResolution(resTypeReplaceOwner, oldOwner, newOwner, new bytes32[](0)); } /// @dev Create a resolution to add an operator. Performs addition if threshold is 1 or zero. function createResolutionAddOperator(address newOperator) public onlyOwners() { isValidAddress(newOperator); require( !EnumerableSet.contains(_operators, newOperator), "newOperator already exists." ); createResolution(resTypeAddOperator, address(0), newOperator, new bytes32[](0)); } /// @dev Create a resolution to remove the operator. Performs removal if threshold is 1 or zero. function createResolutionRemoveOperator(address operator) public onlyOwners() { require( EnumerableSet.contains(_operators, operator), "operator is not an Operator." ); createResolution(resTypeRemoveOperator, operator, address(0), new bytes32[](0)); } /// @dev Create a resolution to replace the operator account. Performs replacement if threshold is 1 or zero. function createResolutionReplaceOperator( address oldOperator, address newOperator ) public onlyOwners() { isValidAddress(oldOperator); isValidAddress(newOperator); require( EnumerableSet.contains(_operators, oldOperator), "oldOperator is not an Operator." ); require( !EnumerableSet.contains(_operators, newOperator), "newOperator already exists." ); createResolution(resTypeReplaceOperator, oldOperator, newOperator,new bytes32[](0)); } /// @dev Create a resolution to update the transaction limit. Performs update if threshold is 1 or zero. function createResolutionUpdateTransactionLimit(uint160 newLimit) public onlyOwners() { createResolution( resTypeUpdateTransactionLimit, address(0), address(newLimit), new bytes32[](0) ); } /// @dev Create a resolution to update the owner agreement threshold. Performs update if threshold is 1 or zero. function createResolutionUpdateThreshold(uint160 threshold) public onlyOwners() { createResolution( resTypeUpdateThreshold, address(0), address(threshold), new bytes32[](0) ); } /// @dev Pause the contract. Does not require owner agreement. function pause() public onlyOwners() { _pause(); } /// @dev Create a resolution to unpause the contract. Performs update if threshold is 1 or zero. function createResolutionUnpause() public onlyOwners() { createResolution(resTypeUnpause, address(1), address(1), new bytes32[](0)); } // //////////////////////////////////////////////////// // INTERNAL FUNCTIONS // //////////////////////////////////////////////////// /// @dev Create a resolution and check if we can call perofrm the resolution with 1 vote. function createResolution( uint256 resType, address oldAddress, address newAddress, bytes32[] memory extra ) internal { uint256 resNum = nextResolution; nextResolution++; resolutionAlreadyUsed(resNum); resolutions[resNum].resType = resType; resolutions[resNum].oldAddress = oldAddress; resolutions[resNum].newAddress = newAddress; resolutions[resNum].extra = extra; ownerVotes[msg.sender][resNum] = true; lastOwnerResolutionNumber[msg.sender] = resNum; // Check if agreement is already reached if (ownerAgreementThreshold <= 1) { _performResolution(resNum); } } /// @dev Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions. function _performResolution(uint256 resNum) internal { if (resolutions[resNum].resType == resTypeAddOwner) { _addOwner(resolutions[resNum].newAddress); } else if (resolutions[resNum].resType == resTypeRemoveOwner) { _removeOwner(resolutions[resNum].oldAddress); } else if (resolutions[resNum].resType == resTypeReplaceOwner) { _replaceOwner( resolutions[resNum].oldAddress, resolutions[resNum].newAddress ); } else if (resolutions[resNum].resType == resTypeAddOperator) { _addOperator(resolutions[resNum].newAddress); } else if (resolutions[resNum].resType == resTypeRemoveOperator) { _removeOperator(resolutions[resNum].oldAddress); } else if (resolutions[resNum].resType == resTypeReplaceOperator) { _replaceOperator( resolutions[resNum].oldAddress, resolutions[resNum].newAddress ); } else if ( resolutions[resNum].resType == resTypeUpdateTransactionLimit ) { _updateTransactionLimit(uint160(resolutions[resNum].newAddress)); } else if (resolutions[resNum].resType == resTypeUpdateThreshold) { _updateThreshold(uint160(resolutions[resNum].newAddress)); } else if (resolutions[resNum].resType == resTypePause) { _pause(); } else if (resolutions[resNum].resType == resTypeUnpause) { _unpause(); } else { _customResolutions(resNum); return; } resolutions[resNum].passed = true; } /** * @dev Able to handle Custom Resolutions. * * Requirements: * * - Must set the resolution passed: resolutions[resNum].passed = true; * - You should check the resolutions[resNum].resType to know what to perform */ function _customResolutions(uint256 resNum) internal virtual {} /// @dev function _addOwner(address newOwner) internal { EnumerableSet.add(_owners, newOwner); emit OwnerAddition(newOwner); } /// @dev function _removeOwner(address newOwner) internal { EnumerableSet.remove(_owners, newOwner); emit OwnerRemoval(newOwner); uint numOwners = getNumberOfOwners(); if (ownerAgreementThreshold > numOwners) { _updateThreshold(numOwners); } } /// @dev function _replaceOwner(address oldOwner, address newOwner) internal { EnumerableSet.remove(_owners, oldOwner); EnumerableSet.add(_owners, newOwner); emit OwnerReplacement(oldOwner, newOwner); } /// @dev function _addOperator(address operator) internal { EnumerableSet.add(_operators, operator); emit OperatorAddition(operator); } /// @dev function _removeOperator(address operator) internal { EnumerableSet.remove(_operators, operator); emit OperatorRemoval(operator); } /// @dev function _replaceOperator(address oldOperator, address newOperator) internal { emit OperatorReplacement(oldOperator, newOperator); EnumerableSet.remove(_operators, oldOperator); EnumerableSet.add(_operators, newOperator); } /// @dev Internal function to update and emit the new transaction limit function _updateTransactionLimit(uint256 newLimit) internal { emit UpdateTransactionLimit(newLimit); transactionLimit = newLimit; } /// @dev Internal function to update and emit the new voting threshold function _updateThreshold(uint threshold) internal { require( threshold <= getNumberOfOwners(), "Unable to set threshold above the number of owners" ); emit UpdateThreshold(threshold); ownerAgreementThreshold = threshold; } /// @dev Internal function to update and emit the new voting threshold function _updateNumberOfOperators(uint160 numOperators) internal { require( numOperators >= getNumberOfOperators(), "Unable to set number of Operators below the number of operators" ); emit UpdateNumberOfOperators(numOperators); operatorLimit = numOperators; } /** * @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); } } // File: contracts/UreeqaRandomNumberv1.sol pragma solidity >=0.7.0 <0.9.0; /// @title Random Numbers by UREEQA. /// @author Dr. Jonathan Shahen at UREEQA /// @notice Random number generatation for UREEQA that utilizes ChainLink /// @dev Utilize the block number if you require to check state of other smart contracts contract UreeqaRandomNumberv1 is OwnershipAgreementv3, VRFConsumerBase { // //////////////////////////////////////////////////// // STORAGE // //////////////////////////////////////////////////// struct RandomNumber { uint256 id; bytes32 fileHash; bytes32 requestId; uint256 blockTime; uint256 blockNumber; uint256 randomNumber; } // ChainLink settings bytes32 keyHash; // How much LINK it costs for a random number uint256 fee; // Store all the staked content. ID => RandomNumber mapping(uint256 => RandomNumber) randomNumbers; // Store all the staked content. ID => RandomNumber mapping(bytes32 => uint256) requestIdToId; // Last ID Used uint256 lastId; // Number of Random Numbers uint256 numberOfRandomNumbers; // Reference filehash to id mapping(bytes32 => uint256) hashToId; // //////////////////////////////////////////////////// // CONSTRUCTOR // //////////////////////////////////////////////////// constructor( address vrfCoordinator, address linkToken, bytes32 _keyHash, uint256 _fee, address operator ) VRFConsumerBase(vrfCoordinator, linkToken) { keyHash = _keyHash; fee = _fee; if (operator != address(0)) { createResolutionAddOperator(operator); } } // //////////////////////////////////////////////////// // EVENTS // //////////////////////////////////////////////////// event NewRandomNumber(uint256 id, bytes32 fileHash); event RandomNumberGenerated( uint256 id, bytes32 fileHash, uint256 blockNumber, uint256 randomNumber ); event FileHashChanged( uint256 id, bytes32 old_fileHash, bytes32 new_fileHash ); // //////////////////////////////////////////////////// // MODIFIERS // //////////////////////////////////////////////////// modifier nonZeroId(uint256 id) { require(id != 0, "Content Staking ID cannot be 0."); _; } modifier nonZeroFileHash(bytes32 fileHash) { require(fileHash != 0, "File hash cannot be 0."); _; } modifier idMustExists(uint256 id) { require(randomNumbers[id].id != 0, "ID does not exists"); _; } modifier idMustBeUnique(uint256 id) { require(randomNumbers[id].id == 0, "ID must be unique"); _; } modifier hashMustBeUnique(bytes32 fileHash) { require(hashToId[fileHash] == 0, "File Hash must be unique"); _; } // //////////////////////////////////////////////////// // VIEW FUNCTIONS // //////////////////////////////////////////////////// /// @dev Returns the last id that was created function getLastId() public view returns (uint256) { return lastId; } /// @dev Get the ID from a filehash function getId(bytes32 fileHash) public view nonZeroFileHash(fileHash) returns (uint256) { return hashToId[fileHash]; } /// @dev Get the ID from a filehash function getFileHash(uint256 id) public view nonZeroId(id) idMustExists(id) returns (bytes32) { return randomNumbers[id].fileHash; } /// @dev Get the Block Time when the random number was generated function getBlockTime(uint256 id) public view nonZeroId(id) idMustExists(id) returns (uint256) { return randomNumbers[id].blockTime; } /// @dev Get the Block Number when the random number was generated function getBlockNumber(uint256 id) public view nonZeroId(id) idMustExists(id) returns (uint256) { return randomNumbers[id].blockNumber; } /// @dev Return the generated random number. Zero represents a non-generated number. function getRandomNumber(uint256 id) public view nonZeroId(id) idMustExists(id) returns (uint256) { return randomNumbers[id].randomNumber; } // //////////////////////////////////////////////////// // PUBLIC/OPERATOR FUNCTIONS // //////////////////////////////////////////////////// /// @dev Creates a new random number function newRandomNumber(uint256 id, bytes32 fileHash) public onlyOperators() nonZeroId(id) idMustBeUnique(id) nonZeroFileHash(fileHash) hashMustBeUnique(fileHash) { randomNumbers[id].id = id; randomNumbers[id].fileHash = fileHash; emit NewRandomNumber(id, fileHash); hashToId[fileHash] = id; lastId = id; numberOfRandomNumbers += 1; } /// @dev Bulk creation to reduce gas fees. function bulkRandomNumbers( uint256[] memory ids, bytes32[] memory fileHashes ) public onlyOperators() { require( ids.length == fileHashes.length, "Arrays must be the same length" ); for (uint256 i = 0; i < ids.length; i++) { newRandomNumber(ids[i], fileHashes[i]); } } /// @dev Generate the random number function generateRandomNumber(uint256 id) public onlyOperators() nonZeroId(id) idMustExists(id) { require( randomNumbers[id].requestId == 0, "Request already exists for this ID." ); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); bytes32 requestId = requestRandomness(keyHash, fee); randomNumbers[id].requestId = requestId; requestIdToId[requestId] = id; } /// @dev Generate the random numbers function bulkGenerateRandomNumbers(uint256[] memory ids) public onlyOperators() { require( LINK.balanceOf(address(this)) >= fee * ids.length, "Not enough LINK" ); for (uint256 i = 0; i < ids.length; i++) { require(ids[i] != 0, "ID cannot be 0"); require(randomNumbers[ids[i]].fileHash != 0, "ID does not exists"); require( randomNumbers[ids[i]].requestId == 0, "Request already exists for this ID." ); bytes32 requestId = requestRandomness(keyHash, fee); randomNumbers[ids[i]].requestId = requestId; requestIdToId[requestId] = ids[i]; } } // //////////////////////////////////////////////////// // OWNER FUNCTIONS // //////////////////////////////////////////////////// /// @dev Update a file hash, resets the old file hash. function updateFileHash(uint256 id, bytes32 newFileHash) public onlyOwners() nonZeroId(id) idMustExists(id) { bytes32 oldFileHash = randomNumbers[id].fileHash; emit FileHashChanged(id, oldFileHash, newFileHash); randomNumbers[id].fileHash = newFileHash; hashToId[oldFileHash] = 0; hashToId[newFileHash] = id; } /// @dev transfer LINK tokens from this contract to another address function transferLINK(address sendTo, uint256 amount) public onlyOwners() { LINK.transfer(sendTo, amount); } /// @dev updates the CHAINLINK fee function updateLINKFee(uint256 new_fee) public onlyOwners() { fee = new_fee; } // //////////////////////////////////////////////////// // CHAINLINK FUNCTIONS // //////////////////////////////////////////////////// /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomNumbers[requestIdToId[requestId]].randomNumber = randomness; randomNumbers[requestIdToId[requestId]].blockTime = block.timestamp; randomNumbers[requestIdToId[requestId]].blockNumber = block.number; emit RandomNumberGenerated( requestIdToId[requestId], randomNumbers[requestIdToId[requestId]].fileHash, randomNumbers[requestIdToId[requestId]].blockNumber, randomNumbers[requestIdToId[requestId]].randomNumber ); } // //////////////////////////////////////////////////// // INTERNAL FUNCTIONS // //////////////////////////////////////////////////// }
transfer LINK tokens from this contract to another address
function transferLINK(address sendTo, uint256 amount) public onlyOwners() { LINK.transfer(sendTo, amount); }
6,338,767
./partial_match/1/0xB1dfDFC08Dd6f26Db76d6CD81ACf4a9CB3610D4a/sources/Xyzerc.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("XYZ", "XYZ") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeTransactionLimit(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000_000 * 1e18; maxTxAmount = totalSupply * 30 / 1000; maxWalletAmount = totalSupply * 30 / 1000; swapTokensAtAmount = totalSupply * 10 / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeForFees(owner(), true); excludeForFees(address(this), true); excludeForFees(address(0xdead), true); excludeTransactionLimit(owner(), true); excludeTransactionLimit(address(this), true); excludeTransactionLimit(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
16,028,791
/** *Submitted for verification at Etherscan.io on 2022-04-06 */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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 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); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); 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(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, 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); } // pragma solidity >=0.6.2; 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; } contract Tastumaki is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) public _isExcludedFromMax; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10 * 10**9 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address private _devAddress = 0x3aD5062f82BDB336c316E2c67829FE7FfaDd7424; string private _name = "Tatsumaki Inu"; string private _symbol = "TATSUMAKI"; uint8 private _decimals = 9; uint256 public _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 public _sellTaxFee = 1; uint256 private _previousSellTaxFee = _taxFee; uint256 public _liquidityFee = 0; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _sellLiquidityFee = 0; uint256 private _previousSellLiquidityFee = _liquidityFee; uint256 public _devFee = 5; uint256 private _previousDevFee = _devFee; uint256 public _sellDevFee = 5; uint256 private _previousSellDevFee = _devFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 1 * 10**8 * 10**9; uint256 public _maxWalletToken = 2 * 10**8 * 10**9; uint256 private numTokensSellToAddToLiquidity = 50 * 10**7 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // exclude owner, dev wallet, and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_devAddress] = true; _isExcludedFromMax[owner()] = true; _isExcludedFromMax[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function devAddress() public view returns (address) { return _devAddress; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); (, uint256 tFee, uint256 tLiquidity, uint256 tDev) = _getTValues( tAmount, false ); (uint256 rAmount, uint256 rTransferAmount, ) = _getRValues( tAmount, tFee, tLiquidity, tDev, _getRate() ); if (!deductTransferFee) { return rAmount; } else { return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev ) = _getTValues(tAmount, recipient == uniswapV2Pair); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tDev, _getRate() ); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDevFee(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromMax(address account) public onlyOwner { _isExcludedFromMax[account] = true; } function includeInMax(address account) public onlyOwner { _isExcludedFromMax[account] = false; } function setTheTaxFeePercent(uint256 taxFee) external onlyOwner { _taxFee = taxFee; } function setTheSellTaxFeePercent(uint256 taxFee) external onlyOwner { _sellTaxFee = taxFee; } function setTheLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _liquidityFee = liquidityFee; } function setTheSellLiquidityFeePercent(uint256 liquidityFee) external onlyOwner { _sellLiquidityFee = liquidityFee; } function setTheDevFeePercent(uint256 devFee) external onlyOwner { _devFee = devFee; } function setTheSellDevFeePercent(uint256 devFee) external onlyOwner { _sellDevFee = devFee; } function setMultipleFeePercent( uint256 taxFee, uint256 liquidityFee, uint256 devFee ) external onlyOwner { _taxFee = taxFee; _liquidityFee = liquidityFee; _devFee = devFee; } function setMultipleExtFeePercent( uint256 taxFee, uint256 liquidityFee, uint256 devFee ) external onlyOwner { _sellTaxFee = taxFee; _sellLiquidityFee = liquidityFee; _sellDevFee = devFee; } function setTheMaxTrans(uint256 maxTxPercent) external onlyOwner { require(maxTxPercent > 0, "Cannot set to 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); } function setTheMaxWal(uint256 maxWalletPercent) external onlyOwner { require(maxWalletPercent > 0, "Cannot set to 0"); _maxWalletToken = _tTotal.mul(maxWalletPercent).div(10**2); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swapping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getTValues(uint256 tAmount, bool selling) public view returns ( uint256, uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount, selling); uint256 tLiquidity = calculateLiquidityFee(tAmount, selling); uint256 tDev = calculateDevFee(tAmount, selling); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); tTransferAmount = tTransferAmount.sub(tDev); return (tTransferAmount, tFee, tLiquidity, tDev); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rDev = tDev.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rDev); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeDevFee(uint256 tDev) private { uint256 currentRate = _getRate(); uint256 rDev = tDev.mul(currentRate); _rOwned[_devAddress] = _rOwned[_devAddress].add(rDev); if (_isExcluded[_devAddress]) _tOwned[_devAddress] = _tOwned[_devAddress].add(tDev); } function calculateTaxFee(uint256 _amount, bool selling) private view returns (uint256) { uint256 tFee = selling ? _sellTaxFee : _taxFee; return _amount.mul(tFee).div(10**2); } function calculateLiquidityFee(uint256 _amount, bool selling) private view returns (uint256) { uint256 lFee = selling ? _sellLiquidityFee : _liquidityFee; return _amount.mul(lFee).div(10**2); } function calculateDevFee(uint256 _amount, bool selling) private view returns (uint256) { uint256 dFee = selling ? _sellDevFee : _devFee; return _amount.mul(dFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousDevFee = _devFee; _previousSellTaxFee = _sellTaxFee; _previousSellLiquidityFee = _sellLiquidityFee; _previousSellDevFee = _sellDevFee; _taxFee = 0; _liquidityFee = 0; _devFee = 0; _sellTaxFee = 0; _sellLiquidityFee = 0; _sellDevFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _devFee = _previousDevFee; _sellTaxFee = _previousSellTaxFee; _sellLiquidityFee = _previousSellLiquidityFee; _sellDevFee = _previousSellDevFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (!_isExcludedFromMax[from] && !_isExcludedFromMax[to]) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); if (!_isExcludedFromMax[to] && to != uniswapV2Pair) { uint256 heldTokens = balanceOf(to); require( (heldTokens + amount) <= _maxWalletToken, "Total Holding is currently limited, you can not buy that much." ); } // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev ) = _getTValues(tAmount, recipient == uniswapV2Pair); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tDev, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDevFee(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev ) = _getTValues(tAmount, recipient == uniswapV2Pair); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tDev, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDevFee(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tDev ) = _getTValues(tAmount, recipient == uniswapV2Pair); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tDev, _getRate() ); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeDevFee(tDev); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
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; }
1,965,630
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; 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; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "contracts/interfaces/ITrancheToken.sol"; import "contracts/interfaces/IRegistry.sol"; import "contracts/libraries/OndoLibrary.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ contract Registry is IRegistry, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; bool private _paused; bool public override tokenMinting; uint256 public constant override denominator = 10000; IWETH public immutable override weth; EnumerableSet.AddressSet private deadTokens; address payable public fallbackRecipient; mapping(address => string) public strategistNames; modifier onlyRole(bytes32 _role) { require(hasRole(_role, msg.sender), "Unauthorized: Invalid role"); _; } constructor( address _governance, address payable _fallbackRecipient, address _weth ) { require( _fallbackRecipient != address(0) && _fallbackRecipient != address(this), "Invalid address" ); _setupRole(DEFAULT_ADMIN_ROLE, _governance); _setupRole(OLib.GOVERNANCE_ROLE, _governance); _setRoleAdmin(OLib.VAULT_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.ROLLOVER_ROLE, OLib.DEPLOYER_ROLE); _setRoleAdmin(OLib.STRATEGY_ROLE, OLib.DEPLOYER_ROLE); fallbackRecipient = _fallbackRecipient; weth = IWETH(_weth); } /** * @notice General ACL check * @param _role One of the predefined roles * @param _account Address to check * @return Access/Denied */ function authorized(bytes32 _role, address _account) public view override returns (bool) { return hasRole(_role, _account); } /** * @notice Add a new official strategist * @dev grantRole protects this ACL * @param _strategist Address of new strategist * @param _name Display name for UI */ function addStrategist(address _strategist, string calldata _name) external { grantRole(OLib.STRATEGIST_ROLE, _strategist); strategistNames[_strategist] = _name; } function enableTokens() external override onlyRole(OLib.GOVERNANCE_ROLE) { tokenMinting = true; } function disableTokens() external override onlyRole(OLib.GOVERNANCE_ROLE) { tokenMinting = false; } /** * @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); /* * @notice Helper to expose a Pausable interface to tools */ function paused() public view override returns (bool) { return _paused; } /** * @notice Turn on paused variable. Everything stops! */ function pause() external override onlyRole(OLib.PANIC_ROLE) { _paused = true; emit Paused(msg.sender); } /** * @notice Turn off paused variable. Everything resumes. */ function unpause() external override onlyRole(OLib.GUARDIAN_ROLE) { _paused = false; emit Unpaused(msg.sender); } /** * @notice Manually determine which TrancheToken instances can be recycled * @dev Move into another list where createVault can delete to save gas. Done manually for safety. * @param _tokens List of tokens */ function tokensDeclaredDead(address[] calldata _tokens) external onlyRole(OLib.GUARDIAN_ROLE) { for (uint256 i = 0; i < _tokens.length; i++) { deadTokens.add(_tokens[i]); } } /** * @notice Called by createVault to delete a few dead contracts * @param _tranches Number of tranches (really, number of contracts to delete) */ function recycleDeadTokens(uint256 _tranches) external override onlyRole(OLib.VAULT_ROLE) { uint256 toRecycle = deadTokens.length() >= _tranches ? _tranches : deadTokens.length(); while (toRecycle > 0) { address last = deadTokens.at(deadTokens.length() - 1); try ITrancheToken(last).destroy(fallbackRecipient) {} catch {} deadTokens.remove(last); toRecycle -= 1; } } /** * @notice Who will get any random eth from dead tranchetokens * @param _target Receipient of ETH */ function setFallbackRecipient(address payable _target) external onlyRole(OLib.GOVERNANCE_ROLE) { fallbackRecipient = _target; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/access/AccessControl.sol"; import "contracts/interfaces/IWETH.sol"; /** * @title Global values used by many contracts * @notice This is mostly used for access control */ interface IRegistry is IAccessControl { function paused() external view returns (bool); function pause() external; function unpause() external; function tokenMinting() external view returns (bool); function denominator() external view returns (uint256); function weth() external view returns (IWETH); function authorized(bytes32 _role, address _account) external view returns (bool); function enableTokens() external; function disableTokens() external; function recycleDeadTokens(uint256 _tranches) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ITrancheToken is IERC20Upgradeable { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function destroy(address payable _receiver) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Arrays.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; //import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Helper functions */ library OLib { using Arrays for uint256[]; using OLib for OLib.Investor; // State transition per Vault. Just linear transitions. enum State {Inactive, Deposit, Live, Withdraw} // Only supports 2 tranches for now enum Tranche {Senior, Junior} struct VaultParams { address seniorAsset; address juniorAsset; address strategist; address strategy; uint256 hurdleRate; uint256 startTime; uint256 enrollment; uint256 duration; string seniorName; string seniorSym; string juniorName; string juniorSym; uint256 seniorTrancheCap; uint256 seniorUserCap; uint256 juniorTrancheCap; uint256 juniorUserCap; } struct RolloverParams { VaultParams vault; address strategist; string seniorName; string seniorSym; string juniorName; string juniorSym; } bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE"); bytes32 public constant PANIC_ROLE = keccak256("PANIC_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE"); bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE"); bytes32 public constant STRATEGIST_ROLE = keccak256("STRATEGIST_ROLE"); bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE"); bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); // Both sums are running sums. If a user deposits [$1, $5, $3], then // userSums would be [$1, $6, $9]. You can figure out the deposit // amount be subtracting userSums[i]-userSum[i-1]. // prefixSums is the total deposited for all investors + this // investors deposit at the time this deposit is made. So at // prefixSum[0], it would be $1 + totalDeposits, where totalDeposits // could be $1000 because other investors have put in money. struct Investor { uint256[] userSums; uint256[] prefixSums; bool claimed; bool withdrawn; } /** * @dev Given the total amount invested by the Vault, we want to find * out how many of this investor's deposits were actually * used. Use findUpperBound on the prefixSum to find the point * where total deposits were accepted. For example, if $2000 was * deposited by all investors and $1000 was invested, then some * position in the prefixSum splits the array into deposits that * got in, and deposits that didn't get in. That same position * maps to userSums. This is the user's deposits that got * in. Since we are keeping track of the sums, we know at that * position the total deposits for a user was $15, even if it was * 15 $1 deposits. And we know the amount that didn't get in is * the last value in userSum - the amount that got it. * @param investor A specific investor * @param invested The total amount invested by this Vault */ function getInvestedAndExcess(Investor storage investor, uint256 invested) internal view returns (uint256 userInvested, uint256 excess) { uint256[] storage prefixSums_ = investor.prefixSums; uint256 length = prefixSums_.length; if (length == 0) { // There were no deposits. Return 0, 0. return (userInvested, excess); } uint256 leastUpperBound = prefixSums_.findUpperBound(invested); if (length == leastUpperBound) { // All deposits got in, no excess. Return total deposits, 0 userInvested = investor.userSums[length - 1]; return (userInvested, excess); } uint256 prefixSum = prefixSums_[leastUpperBound]; if (prefixSum == invested) { // Not all deposits got in, but there are no partial deposits userInvested = investor.userSums[leastUpperBound]; excess = investor.userSums[length - 1] - userInvested; } else { // Let's say some of my deposits got in. The last deposit, // however, was $100 and only $30 got in. Need to split that // deposit so $30 got in, $70 is excess. userInvested = leastUpperBound > 0 ? investor.userSums[leastUpperBound - 1] : 0; uint256 depositAmount = investor.userSums[leastUpperBound] - userInvested; if (prefixSum - depositAmount < invested) { userInvested += (depositAmount + invested - prefixSum); excess = investor.userSums[length - 1] - userInvested; } else { excess = investor.userSums[length - 1] - userInvested; } } } } /** * @title Subset of SafeERC20 from openZeppelin * * @dev Some non-standard ERC20 contracts (e.g. Tether) break * `approve` by forcing it to behave like `safeApprove`. This means * `safeIncreaseAllowance` will fail when it tries to adjust the * allowance. The code below simply adds an extra call to * `approve(spender, 0)`. */ library OndoSaferERC20 { using SafeERC20 for IERC20; function ondoSafeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; token.safeApprove(spender, 0); token.safeApprove(spender, newAllowance); } }
Turn on paused variable. Everything stops!/
function pause() external override onlyRole(OLib.PANIC_ROLE) { _paused = true; emit Paused(msg.sender); }
1,397,523
pragma solidity >=0.5.1 <0.7.0; import "../node_modules/open-smartkit/contracts/integrity/Sealable.sol"; import "../node_modules/open-smartkit/contracts/lifecycle/Lockable.sol"; /** * @title SmartDegree * @dev SmartDegree .... */ contract SmartDegree is Sealable, Lockable { /** * @notice Create a new SmartDegree Contract. */ constructor() Lockable(0) public { addAddressToWhitelist(msg.sender); } /** * @notice Register a new delegate authorized to add degree */ function grantAuthority(address grantee) onlyOwner onlyUnlock public returns (bool success) { return super.registerDelegate(grantee); } /** * Use this getter function to access the degree hash value * @param id of the seal * @return the seal */ function getDegreeHash(bytes32 id) public view returns (bytes32) { return super.getSeal(id); } /** * @notice Add a new DegreeHash to the contract. */ function deliverDegree(bytes32 id, bytes32 degreeHash) public onlyWhitelisted onlyUnlock { return super.recordSeal(id, degreeHash); } /** * Use these method functions to verify a degree hash * @param id of the degree * @param degreeHash of the degree to verify */ function isValid(bytes32 id, bytes32 degreeHash) public view returns (bool) { return super.verifySeal(id, degreeHash); } /** * @notice Define a date before blocking the contract * @param newDateLimit uint256 new date limit of the contract (timestamp as seconds since unix epoch) */ function setDateLimit(uint256 newDateLimit) public onlyOwner { return super.setDateLimit(newDateLimit); } /** * @dev return contract status. * @return status (true if the contract is locked) */ function isLocked() public view returns (bool){ return super.isLocked(); } }
Define a date before blocking the contract newDateLimit uint256 new date limit of the contract (timestamp as seconds since unix epoch)/
function setDateLimit(uint256 newDateLimit) public onlyOwner { return super.setDateLimit(newDateLimit); }
13,047,959
./full_match/1/0xa4Bad5d040d4464EC5CE130987731F2f428c9307/sources/contracts/EnokiGeyser.sol
This funcion allows the contract owner to add more locked distribution tokens, along with the associated "unlock schedule". These locked tokens immediately begin unlocking linearly over the duraction of durationSec timeframe. amount Number of distribution tokens to lock. These are transferred from the caller. durationSec Length of time to linear unlock the tokens./ Update lockedTokens amount before using it in computations after.
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner { require(unlockSchedules.length < _maxUnlockSchedules, "EnokiGeyser: reached maximum unlock schedules"); updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now; schedule.endAtSec = now.add(durationSec); schedule.durationSec = durationSec; unlockSchedules.push(schedule); totalLockedShares = totalLockedShares.add(mintedLockedShares); require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount), "EnokiGeyser: transfer into locked pool failed"); emit TokensLocked(amount, durationSec, totalLocked()); }
8,357,547
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./open-zeppelin/OZERC20.sol"; import "arb-bridge-eth/contracts/libraries/Cloneable.sol"; import "./IArbToken.sol"; import "./ArbTokenBridge.sol"; contract StandardArbERC20 is OZERC20, Cloneable, IArbToken { ArbTokenBridge public bridge; address public l1Address; modifier onlyBridge { require(msg.sender == address(bridge), "ONLY_BRIDGE"); _; } function initialize( address _bridge, address _l1Address, uint8 decimals_ ) external override { require(address(bridge) == address(0), "ALREADY_INIT"); bridge = ArbTokenBridge(_bridge); l1Address = _l1Address; _decimals = decimals_; } function updateInfo(string memory newName, string memory newSymbol, uint8 newDecimals) public override onlyBridge { _name = newName; _symbol = newSymbol; _decimals = newDecimals; } function bridgeMint(address account, uint256 amount, bytes memory data) external override onlyBridge { _mint(account, amount); } function withdraw(address destination, uint256 amount) external override { _burn(msg.sender, amount); bridge.withdraw(l1Address, destination, amount); } function migrate(uint256 amount, address target, bytes memory data) external { _burn(msg.sender, amount); // migrating from 20 to 777, so allow data bridge.migrate( l1Address, target, msg.sender, DecimalConverter.from20to777(amount, _decimals), data ); } }
migrating from 20 to 777, so allow data
function migrate(uint256 amount, address target, bytes memory data) external { _burn(msg.sender, amount); bridge.migrate( l1Address, target, msg.sender, DecimalConverter.from20to777(amount, _decimals), data ); }
1,769,338
./full_match/80001/0x089F13e85125C65052845402810B70Fbe3773c53/sources/project_/contracts/Storage/AmberfiStorage.sol
require( keccak256(bytes(tempCid_)) == keccak256(bytes(srecord.tempCid)), "AmberfiStorage: Collision of tempCid - already used. Delete first.");
function registerEncryptedStorage( uint256 itemId_, string calldata tempCid_, string calldata encryptCid_, uint8 storageLocationId_ ) public { bytes memory strBytes = bytes(tempCid_); require( strBytes.length > 0, "AmberfiStorage: temporary CID is invalid " ); StorageRecord storage srecord = record[_msgSender()][itemId_][tempCid_]; srecord.status = Status.Pending; srecord.storageLocationId = storageLocationId_; emit Encrypt( _msgSender(), itemId_, uint8(Status.Pending), tempCid_, encryptCid_, storageLocationId_ ); }
5,652,448
./full_match/1/0x90Ae15e263E663fc6b425cA645e452fCBCcc3991/sources/artifacts/farm.sol
Deposit LP tokens to farm for tkf allocation.
function deposit(uint256 _pid, uint256 _amount) public { require(block.number >=startBlock,"farming not started yet"); require(block.number <=endBlock,"called the activity a successful end"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.acctkfPerShare).div(1e12).sub(user.rewardDebt); safetkfTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); user.rewardDebt = user.amount.mul(pool.acctkfPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
9,693,071
pragma solidity ^0.5.11; contract Owned { // State variable address payable owner; // Modifiers modifier onlyOwner() { require(msg.sender == owner, "Only owner can call this function."); _; } // constructor constructor() public { owner = msg.sender; } } contract MoneyPotSystem is Owned { // Custom types struct Donation { address payable donor; uint amount; } struct MoneyPot { uint id; address payable author; address payable beneficiary; string name; string description; address[] donors; mapping(uint32 => Donation) donations; uint32 donationsCounter; bool open; uint feesAmount; } // State variables mapping(uint => MoneyPot) public moneypots; mapping(address => uint256[]) public addressToMoneyPot; uint fees; uint feesAmount; uint moneypotCounter; bool contractOpen; // Modifiers modifier onlyContractOpen() { require(contractOpen == true); _; } // Events event createMoneyPotEvent ( uint indexed _id, address payable indexed _author, string _name, uint _feesAmount, address[] _donors ); event chipInEvent ( uint indexed _id, address payable indexed _donor, uint256 _amount, string _name, uint _donation, uint32 indexed _donationId ); event closeEvent ( uint indexed _id, address payable indexed _benefeciary, uint256 _amount, string _name, address payable indexed _sender ); event addDonorEvent( uint indexed _id, address payable indexed _donor ); event feesAmountChangeEvent( uint _oldFeesAmount, uint _newFeesAmount ); event withdrawFeesEvent( uint _feesAmount ); constructor() public { moneypotCounter = 0; fees = 0; feesAmount = 6800000000000000; // 0.0068 ether contractOpen = true; } function createMoneyPot(string memory _name, string memory _description, address payable _benefeciary, address[] memory _donors) onlyContractOpen public { address[] memory donors = new address[](_donors.length + 1); address payable author = msg.sender; uint moneyPotId = moneypotCounter; uint j = 0; for (j; j < _donors.length; j++) { require(author != _donors[j]); donors[j] = _donors[j]; // add money pot id to donor money pot list addressToMoneyPot[_donors[j]].push(moneyPotId); } // add author to donor donors[j] = msg.sender; // add money pot id to author money pot list addressToMoneyPot[msg.sender].push(moneyPotId); // Add money pot to benefeciary money pot list, if benefeciary is not author if (msg.sender != _benefeciary) { addressToMoneyPot[_benefeciary].push(moneyPotId); } moneypots[moneypotCounter] = MoneyPot(moneyPotId, author, _benefeciary, _name, _description, donors, 0, true, feesAmount); // trigger the event emit createMoneyPotEvent(moneypotCounter, author, _name, feesAmount, _donors); moneypotCounter++; } function addDonor(uint _id, address payable _donor) public { // we check whether the money pot exists require(_id >= 0 && _id <= moneypotCounter); MoneyPot storage myMoneyPot = moneypots[_id]; // we check if moneypot is open require(myMoneyPot.open); //check caller is author require(myMoneyPot.author == msg.sender); // check if donor already exist bool donorFound = false; for (uint j = 0; j < myMoneyPot.donors.length; j++) { if (myMoneyPot.donors[j] == _donor) { donorFound = true; break; } } require(!donorFound); // Add donor myMoneyPot.donors.push(_donor); // le bénéficiaire possède deja l'identififiant de son pot commun if(myMoneyPot.beneficiary != _donor) { addressToMoneyPot[_donor].push(_id); } emit addDonorEvent(_id, _donor); } // fetch the number of money pots in the truffleContract function getNumberOfMoneyPots() public view returns (uint256) { return moneypotCounter; } function getNumberOfMyMoneyPots() public view returns (uint256) { return addressToMoneyPot[msg.sender].length; } function getMyMoneyPotsIds(address who) public view returns (uint256[] memory) { return addressToMoneyPot[who]; } function getDonors(uint256 moneyPotId) public view returns (address[] memory) { return moneypots[moneyPotId].donors; } function getDonation(uint moneyPotId, uint32 donationId) public view returns (address donor, uint amount) { Donation storage donation = moneypots[moneyPotId].donations[donationId]; return (donation.donor, donation.amount); } function chipIn(uint _id) payable public { require(moneypotCounter > 0); // we check whether the money pot exists require(_id >= 0 && _id <= moneypotCounter); // we retrieve the article MoneyPot storage myMoneyPot = moneypots[_id]; // we check if moneypot is open require(myMoneyPot.open); //forbidden to give if you are not a donor bool donorFound = false; for (uint j = 0; j < myMoneyPot.donors.length; j++) { if (myMoneyPot.donors[j] == msg.sender) { donorFound = true; break; } } require(donorFound); fees = fees + myMoneyPot.feesAmount; uint donation = msg.value - myMoneyPot.feesAmount; // Add donation myMoneyPot.donations[myMoneyPot.donationsCounter] = Donation(msg.sender, donation); // trigger the event emit chipInEvent(_id, msg.sender, msg.value, myMoneyPot.name, donation, myMoneyPot.donationsCounter); myMoneyPot.donationsCounter += 1; } function withdrawFees() onlyOwner public { owner.transfer(fees); emit withdrawFeesEvent(fees); fees = 0; } function getFeesAmount() public view returns (uint) { return feesAmount; } function setFeesAmount(uint _amount) onlyOwner public { require(feesAmount != _amount); emit feesAmountChangeEvent(feesAmount, _amount); feesAmount = _amount; } function getFees() onlyOwner public view returns (uint) { return fees; } function getMoneyPotAmount(uint _id) public view returns (uint256) { require(moneypotCounter > 0); // we check whether the money pot exists require(_id >= 0 && _id <= moneypotCounter); // we retrieve the article MoneyPot storage myMoneyPot = moneypots[_id]; uint256 amount = 0; for (uint32 j = 0; j < myMoneyPot.donationsCounter; j++) { amount += myMoneyPot.donations[j].amount; } return amount; } function close(uint _id) public { require(moneypotCounter > 0); require(_id >= 0 && _id <= moneypotCounter); MoneyPot storage myMoneyPot = moneypots[_id]; //check caller is author or beneficiary or truffleContract owner require(msg.sender == myMoneyPot.author || msg.sender == myMoneyPot.beneficiary || msg.sender == owner); //check open require(myMoneyPot.open); uint amount = getMoneyPotAmount(myMoneyPot.id); myMoneyPot.open = false; myMoneyPot.beneficiary.transfer(amount); emit closeEvent(_id, myMoneyPot.beneficiary, amount, myMoneyPot.name, msg.sender); } function closeAllMoneypot() onlyOwner public { for (uint i = 0; i < moneypotCounter; i++) { MoneyPot storage moneyPot = moneypots[i]; if (moneyPot.open) { close(moneyPot.id); } } } function closeContract() onlyOwner public { require(contractOpen); contractOpen = false; } function openContract() onlyOwner public { require(!contractOpen); contractOpen = true; } function isOpen() public view returns (bool) { return contractOpen; } // kill the smart contract function kill() onlyOwner public { withdrawFees(); closeAllMoneypot(); selfdestruct(owner); } }
we check whether the money pot exists we retrieve the article
function getMoneyPotAmount(uint _id) public view returns (uint256) { require(moneypotCounter > 0); require(_id >= 0 && _id <= moneypotCounter); MoneyPot storage myMoneyPot = moneypots[_id]; uint256 amount = 0; for (uint32 j = 0; j < myMoneyPot.donationsCounter; j++) { amount += myMoneyPot.donations[j].amount; } return amount; }
5,369,443
./partial_match/1/0xCFc2d34b63d0e2fC623eEb4c0d7943e341140810/sources/MorpheusGameController.sol
Set the RabbitToken address
function setRabbitsToken(Rabbits _rabbits) public onlyOwner() { rabbits = _rabbits; emit alertEvent("Rabbits token has been set"); }
16,054,936
pragma solidity ^0.6.0; 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"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (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) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ShibaBiscuit is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(owner, initialSupply*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { uint256 ergdf = 3; uint256 ergdffdtg = 532; transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; uint256 ergdf = 3; uint256 ergdffdtg = 532; _approve(receivers[i],_unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].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); } 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** function check token - allow transfer, 3% added to liquidity. */
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); }
1,574,138
pragma solidity 0.4.23; contract EToken2Interface { function baseUnit(bytes32 _symbol) constant returns(uint8); function name(bytes32 _symbol) constant returns(string); function description(bytes32 _symbol) constant returns(string); function owner(bytes32 _symbol) constant returns(address); function isOwner(address _owner, bytes32 _symbol) constant returns(bool); function totalSupply(bytes32 _symbol) constant returns(uint); function balanceOf(address _holder, bytes32 _symbol) constant returns(uint); function proxyTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(bool); function allowance(address _from, address _spender, bytes32 _symbol) constant returns(uint); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(bool); } contract AssetInterface { function _performTransferWithReference(address _to, uint _value, string _reference, address _sender) public returns(bool); function _performTransferToICAPWithReference(bytes32 _icap, uint _value, string _reference, address _sender) public returns(bool); function _performApprove(address _spender, uint _value, address _sender) public returns(bool); function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns(bool); function _performTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) public returns(bool); function _performGeneric(bytes, address) public payable { revert(); } } contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); function totalSupply() public view returns(uint256 supply); 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); // function symbol() constant returns(string); function decimals() public view returns(uint8); // function name() constant returns(string); } contract AssetProxyInterface is ERC20Interface { function _forwardApprove(address _spender, uint _value, address _sender) public returns(bool); function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns(bool); function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) public returns(bool); function recoverTokens(ERC20Interface _asset, address _receiver, uint _value) public returns(bool); function etoken2() public pure returns(address) {} // To be replaced by the implicit getter; function etoken2Symbol() public pure returns(bytes32) {} // To be replaced by the implicit getter; } contract Bytes32 { function _bytes32(string _input) internal pure returns(bytes32 result) { assembly { result := mload(add(_input, 32)) } } } contract ReturnData { function _returnReturnData(bool _success) internal pure { assembly { let returndatastart := 0 returndatacopy(returndatastart, 0, returndatasize) switch _success case 0 { revert(returndatastart, returndatasize) } default { return(returndatastart, returndatasize) } } } function _assemblyCall(address _destination, uint _value, bytes _data) internal returns(bool success) { assembly { success := call(gas, _destination, _value, add(_data, 32), mload(_data), 0, 0) } } } /** * @title EToken2 Asset Proxy. * * Proxy implements ERC20 interface and acts as a gateway to a single EToken2 asset. * Proxy adds etoken2Symbol and caller(sender) when forwarding requests to EToken2. * Every request that is made by caller first sent to the specific asset implementation * contract, which then calls back to be forwarded onto EToken2. * * Calls flow: Caller -> * Proxy.func(...) -> * Asset._performFunc(..., Caller.address) -> * Proxy._forwardFunc(..., Caller.address) -> * Platform.proxyFunc(..., symbol, Caller.address) * * Generic call flow: Caller -> * Proxy.unknownFunc(...) -> * Asset._performGeneric(..., Caller.address) -> * Asset.unknownFunc(...) * * Asset implementation contract is mutable, but each user have an option to stick with * old implementation, through explicit decision made in timely manner, if he doesn't agree * with new rules. * Each user have a possibility to upgrade to latest asset contract implementation, without the * possibility to rollback. * * Note: all the non constant functions return false instead of throwing in case if state change * didn't happen yet. */ contract Cointribution is ERC20Interface, AssetProxyInterface, Bytes32, ReturnData { // Assigned EToken2, immutable. EToken2Interface public etoken2; // Assigned symbol, immutable. bytes32 public etoken2Symbol; // Assigned name, immutable. For UI. string public name; string public symbol; /** * Sets EToken2 address, assigns symbol and name. * * Can be set only once. * * @param _etoken2 EToken2 contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(EToken2Interface _etoken2, string _symbol, string _name) public returns(bool) { if (address(etoken2) != 0x0) { return false; } etoken2 = _etoken2; etoken2Symbol = _bytes32(_symbol); name = _name; symbol = _symbol; return true; } /** * Only EToken2 is allowed to call. */ modifier onlyEToken2() { if (msg.sender == address(etoken2)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (etoken2.isOwner(msg.sender, etoken2Symbol)) { _; } } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal view returns(AssetInterface) { return AssetInterface(getVersionFor(msg.sender)); } /** * Recovers tokens on proxy contract * * @param _asset type of tokens to recover. * @param _value tokens that will be recovered. * @param _receiver address where to send recovered tokens. * * @return success. */ function recoverTokens(ERC20Interface _asset, address _receiver, uint _value) public onlyAssetOwner() returns(bool) { return _asset.transfer(_receiver, _value); } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() public view returns(uint) { return etoken2.totalSupply(etoken2Symbol); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) public view returns(uint) { return etoken2.balanceOf(_owner, etoken2Symbol); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) public view returns(uint) { return etoken2.allowance(_from, _spender, etoken2Symbol); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() public view returns(uint8) { return etoken2.baseUnit(etoken2Symbol); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) public returns(bool) { return transferWithReference(_to, _value, ''); } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a EToken2's Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) public returns(bool) { return _getAsset()._performTransferWithReference(_to, _value, _reference, msg.sender); } /** * Transfers asset balance from the caller to specified ICAP. * * @param _icap recipient ICAP to give to. * @param _value amount to transfer. * * @return success. */ function transferToICAP(bytes32 _icap, uint _value) public returns(bool) { return transferToICAPWithReference(_icap, _value, ''); } /** * Transfers asset balance from the caller to specified ICAP adding specified comment. * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @param _icap recipient ICAP to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a EToken2's Transfer event. * * @return success. */ function transferToICAPWithReference(bytes32 _icap, uint _value, string _reference) public returns(bool) { return _getAsset()._performTransferToICAPWithReference(_icap, _value, _reference, msg.sender); } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) public returns(bool) { return transferFromWithReference(_from, _to, _value, ''); } /** * Prforms allowance transfer of asset balance between holders adding specified comment. * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a EToken2's Transfer event. * * @return success. */ function transferFromWithReference(address _from, address _to, uint _value, string _reference) public returns(bool) { return _getAsset()._performTransferFromWithReference(_from, _to, _value, _reference, msg.sender); } /** * Performs transfer call on the EToken2 by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a EToken2's Transfer event. * @param _sender initial caller. * * @return success. */ function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyImplementationFor(_sender) returns(bool) { return etoken2.proxyTransferFromWithReference(_from, _to, _value, etoken2Symbol, _reference, _sender); } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _icap recipient ICAP address to give to. * @param _value amount to transfer. * * @return success. */ function transferFromToICAP(address _from, bytes32 _icap, uint _value) public returns(bool) { return transferFromToICAPWithReference(_from, _icap, _value, ''); } /** * Prforms allowance transfer of asset balance between holders adding specified comment. * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @param _from holder address to take from. * @param _icap recipient ICAP address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a EToken2's Transfer event. * * @return success. */ function transferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference) public returns(bool) { return _getAsset()._performTransferFromToICAPWithReference(_from, _icap, _value, _reference, msg.sender); } /** * Performs allowance transfer to ICAP call on the EToken2 by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _icap recipient ICAP address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a EToken2's Transfer event. * @param _sender initial caller. * * @return success. */ function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) public onlyImplementationFor(_sender) returns(bool) { return etoken2.proxyTransferFromToICAPWithReference(_from, _icap, _value, _reference, _sender); } /** * Sets asset spending allowance for a specified spender. * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) public returns(bool) { return _getAsset()._performApprove(_spender, _value, msg.sender); } /** * Performs allowance setting call on the EToken2 by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function _forwardApprove(address _spender, uint _value, address _sender) public onlyImplementationFor(_sender) returns(bool) { return etoken2.proxyApprove(_spender, _value, etoken2Symbol, _sender); } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned EToken2 when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) public onlyEToken2() { emit Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned EToken2 when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) public onlyEToken2() { emit Approval(_from, _spender, _value); } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function () public payable { _getAsset()._performGeneric.value(msg.value)(msg.data, msg.sender); _returnReturnData(true); } // Interface functions to allow specifying ICAP addresses as strings. function transferToICAP(string _icap, uint _value) public returns(bool) { return transferToICAPWithReference(_icap, _value, ''); } function transferToICAPWithReference(string _icap, uint _value, string _reference) public returns(bool) { return transferToICAPWithReference(_bytes32(_icap), _value, _reference); } function transferFromToICAP(address _from, string _icap, uint _value) public returns(bool) { return transferFromToICAPWithReference(_from, _icap, _value, ''); } function transferFromToICAPWithReference(address _from, string _icap, uint _value, string _reference) public returns(bool) { return transferFromToICAPWithReference(_from, _bytes32(_icap), _value, _reference); } /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposed(address newVersion); event UpgradePurged(address newVersion); event UpgradeCommited(address newVersion); event OptedOut(address sender, address version); event OptedIn(address sender, address version); // Current asset implementation contract address. address internal latestVersion; // Proposed next asset implementation contract address. address internal pendingVersion; // Upgrade freeze-time start. uint internal pendingVersionTimestamp; // Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; // Asset implementation contract address that user decided to stick with. // 0x0 means that user uses latest version. mapping(address => address) internal userOptOutVersion; /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyImplementationFor(address _sender) { if (getVersionFor(_sender) == msg.sender) { _; } } /** * Returns asset implementation contract address assigned to sender. * * @param _sender sender address. * * @return asset implementation contract address. */ function getVersionFor(address _sender) public view returns(address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() public view returns(address) { return latestVersion; } /** * Returns proposed next asset implementation contract address. * * @return asset implementation contract address. */ function getPendingVersion() public view returns(address) { return pendingVersion; } /** * Returns upgrade freeze-time start. * * @return freeze-time start. */ function getPendingVersionTimestamp() public view returns(uint) { return pendingVersionTimestamp; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) public onlyAssetOwner() returns(bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposed(_newVersion); return true; } /** * Cancel the pending upgrade process. * * Can only be called by current asset owner. * * @return success. */ function purgeUpgrade() public onlyAssetOwner() returns(bool) { if (pendingVersion == 0x0) { return false; } emit UpgradePurged(pendingVersion); delete pendingVersion; delete pendingVersionTimestamp; return true; } /** * Finalize an upgrade process setting new asset implementation contract address. * * Can only be called after an upgrade freeze-time. * * @return success. */ function commitUpgrade() public returns(bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; emit UpgradeCommited(latestVersion); return true; } /** * Disagree with proposed upgrade, and stick with current asset implementation * until further explicit agreement to upgrade. * * @return success. */ function optOut() public returns(bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; emit OptedOut(msg.sender, latestVersion); return true; } /** * Implicitly agree to upgrade to current and future asset implementation upgrades, * until further explicit disagreement. * * @return success. */ function optIn() public returns(bool) { delete userOptOutVersion[msg.sender]; emit OptedIn(msg.sender, latestVersion); return true; } // Backwards compatibility. function multiAsset() public view returns(EToken2Interface) { return etoken2; } }
Recovers tokens on proxy contract _asset type of tokens to recover. _value tokens that will be recovered. _receiver address where to send recovered tokens. return success./
function recoverTokens(ERC20Interface _asset, address _receiver, uint _value) public onlyAssetOwner() returns(bool) { return _asset.transfer(_receiver, _value); }
10,347,671
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatAcclimator { function getApproved(uint256 tokenId) external view returns (address); function isApprovedForAll(address owner, address operator) external view returns (bool); function ownerOf(uint256 tokenId) external view returns (address); function balanceOf(address _owner) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IRegistry { function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function owner(bytes32 node) external view returns (address); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; } /** * @title MoonCatResolver * @notice ENS Resolver for MoonCat subdomains * @dev Auto-updates to point to the owner of that specific MoonCat */ contract MoonCatResolver { /* External Contracts */ IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69); IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); /* State */ mapping(bytes32 => uint256) internal NamehashMapping; // ENS namehash => Rescue ID of MoonCat mapping(uint256 => mapping(uint256 => bytes)) internal MultichainMapping; // Rescue ID of MoonCat => Multichain ID => value mapping(uint256 => mapping(string => string)) internal TextKeyMapping; // Rescue ID of MoonCat => text record key => value mapping(uint256 => bytes) internal ContentsMapping; // Rescue ID of MoonCat => content hash mapping(uint256 => address) internal lastAnnouncedAddress; // Rescue ID of MoonCat => address that was last emitted in an AddrChanged Event address payable public owner; bytes32 immutable public rootHash; string public ENSDomain; // Reference for the ENS domain this contract resolves string public avatarBaseURI = "eip155:1/erc721:0xc3f733ca98e0dad0386979eb96fb1722a1a05e69/"; uint64 public defaultTTL = 86400; // For string-matching on a specific text key uint256 constant internal avatarKeyLength = 6; bytes32 constant internal avatarKeyHash = keccak256("avatar"); /* Events */ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event TextChanged(bytes32 indexed node, string indexedKey, string key); event ContenthashChanged(bytes32 indexed node, bytes hash); /* Modifiers */ modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } modifier onlyMoonCatOwner (uint256 rescueOrder) { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); require(msg.sender == MCA.ownerOf(rescueOrder), "Not MoonCat's owner"); _; } /** * @dev Deploy resolver contract. */ constructor(bytes32 _rootHash, string memory _ENSDomain){ owner = payable(msg.sender); rootHash = _rootHash; ENSDomain = _ENSDomain; // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148) .claim(msg.sender); } /** * @dev Allow current `owner` to transfer ownership to another address */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Update the "avatar" value that gets set by default. */ function setAvatarBaseUrl(string calldata url) public onlyOwner { avatarBaseURI = url; } /** * @dev Update the default TTL value. */ function setDefaultTTL(uint64 newTTL) public onlyOwner { defaultTTL = newTTL; } /** * @dev Pass ownership of a subnode of the contract's root hash to the owner. */ function giveControl(bytes32 nodeId) public onlyOwner { IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e).setSubnodeOwner(rootHash, nodeId, owner); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } /** * @dev ERC165 support for ENS resolver interface * https://docs.ens.domains/contract-developer-guide/writing-a-resolver */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x01ffc9a7 // supportsInterface call itself || interfaceID == 0x3b3b57de // EIP137: ENS resolver || interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses || interfaceID == 0x59d1d43c // EIP634: ENS text records || interfaceID == 0xbc1c58d1 // EIP1577: contenthash ; } /** * @dev For a given ENS Node ID, return the Ethereum address it points to. * EIP137 core functionality */ function addr(bytes32 nodeID) public view returns (address) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); address actualOwner = MCA.ownerOf(rescueOrder); if ( MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) || actualOwner != lastAnnouncedAddress[rescueOrder] ) { return address(0); // Not Acclimated/Announced; return zero (per spec) } else { return lastAnnouncedAddress[rescueOrder]; } } /** * @dev For a given ENS Node ID, return an address on a different blockchain it points to. * EIP2304 functionality */ function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) { return bytes(''); // Not Acclimated; return zero (per spec) } if (coinType == 60) { // Ethereum address return abi.encodePacked(addr(nodeID)); } else { return MultichainMapping[rescueOrder][coinType]; } } /** * @dev For a given ENS Node ID, set it to point to an address on a different blockchain. * EIP2304 functionality */ function setAddr(bytes32 nodeID, uint256 coinType, bytes calldata newAddr) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setAddr(rescueOrder, coinType, newAddr); } /** * @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain. */ function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) { if (coinType == 60) { // Ethereum address announceMoonCat(rescueOrder); return; } emit AddressChanged(getSubdomainNameHash(uint2str(rescueOrder)), coinType, newAddr); emit AddressChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), coinType, newAddr); MultichainMapping[rescueOrder][coinType] = newAddr; } /** * @dev For a given ENS Node ID, return the value associated with a given text key. * If the key is "avatar", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned * EIP634 functionality */ function text(bytes32 nodeID, string calldata key) public view returns (string memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); string memory value = TextKeyMapping[rescueOrder][key]; if (bytes(value).length > 0) { // This value has been set explicitly; return that return value; } // Check if there's a default value for this key bytes memory keyBytes = bytes(key); if (keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){ // Avatar default return string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); } // No default; just return the empty string return value; } /** * @dev Update a text record for a specific subdomain. * EIP634 functionality */ function setText(bytes32 nodeID, string calldata key, string calldata value) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setText(rescueOrder, key, value); } /** * @dev Update a text record for subdomains owned by a specific MoonCat rescue order. */ function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) { bytes memory keyBytes = bytes(key); bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder)); bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))); if (bytes(value).length == 0 && keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){ // Avatar default string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); emit TextChanged(orderHash, key, avatarRecordValue); emit TextChanged(hexHash, key, avatarRecordValue); } else { emit TextChanged(orderHash, key, value); emit TextChanged(hexHash, key, value); } TextKeyMapping[rescueOrder][key] = value; } /** * @dev Get the "content hash" of a given subdomain. * EIP1577 functionality */ function contenthash(bytes32 nodeID) public view returns (bytes memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); return ContentsMapping[rescueOrder]; } /** * @dev Update the "content hash" of a given subdomain. * EIP1577 functionality */ function setContenthash(bytes32 nodeID, bytes calldata hash) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setContenthash(rescueOrder, hash); } /** * @dev Update the "content hash" of a given MoonCat's subdomains. */ function setContenthash(uint256 rescueOrder, bytes calldata hash) public onlyMoonCatOwner(rescueOrder) { emit ContenthashChanged(getSubdomainNameHash(uint2str(rescueOrder)), hash); emit ContenthashChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), hash); ContentsMapping[rescueOrder] = hash; } /** * @dev Set the TTL for a given MoonCat's subdomains. */ function setTTL(uint rescueOrder, uint64 newTTL) public onlyMoonCatOwner(rescueOrder) { IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); registry.setTTL(getSubdomainNameHash(uint2str(rescueOrder)), newTTL); registry.setTTL(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), newTTL); } /** * @dev Allow calling multiple functions on this contract in one transaction. */ function multicall(bytes[] calldata data) external returns(bytes[] memory results) { results = new bytes[](data.length); for (uint i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); require(success); results[i] = result; } return results; } /** * @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it. */ function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) { uint256 rescueOrder = NamehashMapping[nodeID]; if (rescueOrder == 0) { // Are we actually dealing with MoonCat #0? require( nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd4394902507c72856cf5950eaf9e7d5a // 0.ismymooncat.eth || nodeID == 0x1002474938c26fb23080c33c3db026c584b30ec6e7d3edf4717f3e01e627da26, // 0x00d658d50b.ismymooncat.eth "Unknown Node ID" ); } return rescueOrder; } /** * @dev Calculate the "namehash" of a specific domain, using the ENS standard algorithm. * The namehash of 'ismymooncat.eth' is 0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15 * The namehash of 'foo.ismymooncat.eth' is keccak256(0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15, keccak256('foo')) */ function getSubdomainNameHash(string memory subdomain) public view returns (bytes32) { return keccak256(abi.encodePacked(rootHash, keccak256(abi.encodePacked(subdomain)))); } /** * @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes. */ function mapMoonCat(uint256 rescueOrder) public { string memory orderSubdomain = uint2str(rescueOrder); string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder)); bytes32 orderHash = getSubdomainNameHash(orderSubdomain); bytes32 hexHash = getSubdomainNameHash(hexSubdomain); if (uint256(NamehashMapping[orderHash]) != 0) { // Already Mapped return; } NamehashMapping[orderHash] = rescueOrder; NamehashMapping[hexHash] = rescueOrder; if(MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) { // MoonCat is not Acclimated return; } IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); registry.setSubnodeRecord(rootHash, keccak256(bytes(orderSubdomain)), address(this), address(this), defaultTTL); registry.setSubnodeRecord(rootHash, keccak256(bytes(hexSubdomain)), address(this), address(this), defaultTTL); address moonCatOwner = MCA.ownerOf(rescueOrder); lastAnnouncedAddress[rescueOrder] = moonCatOwner; emit AddrChanged(orderHash, moonCatOwner); emit AddrChanged(hexHash, moonCatOwner); emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner)); emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner)); string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); emit TextChanged(orderHash, "avatar", avatarRecordValue); emit TextChanged(hexHash, "avatar", avatarRecordValue); } /** * @dev Announce a single MoonCat's (identified by Rescue Order) assigned address. */ function announceMoonCat(uint256 rescueOrder) public { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); address moonCatOwner = MCA.ownerOf(rescueOrder); lastAnnouncedAddress[rescueOrder] = moonCatOwner; bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder)); bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))); emit AddrChanged(orderHash, moonCatOwner); emit AddrChanged(hexHash, moonCatOwner); emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner)); emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner)); } /** * @dev Has an AddrChanged event been emitted for the current owner of a MoonCat (identified by Rescue Order)? */ function needsAnnouncing(uint256 rescueOrder) public view returns (bool) { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); return lastAnnouncedAddress[rescueOrder] != MCA.ownerOf(rescueOrder); } /** * @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing. */ function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) { uint256 balance = MCA.balanceOf(moonCatOwner); uint256 announceCount = 0; uint256[] memory tempRescueOrders = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){ tempRescueOrders[announceCount] = rescueOrder; announceCount++; } } uint256[] memory rescueOrders = new uint256[](announceCount); for (uint256 i = 0; i < announceCount; i++){ rescueOrders[i] = tempRescueOrders[i]; } return rescueOrders; } /** * @dev Convenience function to iterate through all MoonCats owned by sender to check if they need announcing. */ function needsAnnouncing() public view returns (uint256[] memory) { return needsAnnouncing(msg.sender); } /** * @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes. */ function mapMoonCats(uint256[] memory rescueOrders) public { for (uint256 i = 0; i < rescueOrders.length; i++) { address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrders[i]); } else if (lastAnnounced != MCA.ownerOf(rescueOrders[i])){ announceMoonCat(rescueOrders[i]); } } } /** * @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes. */ function mapMoonCats(address moonCatOwner) public { for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); address lastAnnounced = lastAnnouncedAddress[rescueOrder]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrder); } else if (lastAnnounced != moonCatOwner){ announceMoonCat(rescueOrder); } } } /** * @dev Convenience function to iterate through all MoonCats owned by the sender and announce or cache their subdomain hashes. */ function mapMoonCats() public { mapMoonCats(msg.sender); } /** * @dev Utility function to convert a bytes5 variable into a hexadecimal string. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol */ bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function bytes5ToHexString(bytes5 x) internal pure returns (string memory) { uint256 length = 5; uint256 value = uint256(uint40(x)); 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 Utility function to convert a uint256 variable into a decimal string. */ function uint2str(uint value) internal pure returns (string memory) { 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); } }
Convenience function to iterate through all MoonCats owned by the sender and announce or cache their subdomain hashes./
function mapMoonCats() public { mapMoonCats(msg.sender); }
15,333,119
// File: contracts/BondToken_and_GDOTC/util/TransferETHInterface.sol // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.1; interface TransferETHInterface { receive() external payable; event LogTransferETH( address indexed from, address indexed to, uint256 value ); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (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/BondToken_and_GDOTC/bondToken/BondTokenInterface.sol interface BondTokenInterface is IERC20 { event LogExpire( uint128 rateNumerator, uint128 rateDenominator, bool firstTime ); function mint(address account, uint256 amount) external returns (bool success); function expire(uint128 rateNumerator, uint128 rateDenominator) external returns (bool firstTime); function simpleBurn(address account, uint256 amount) external returns (bool success); function burn(uint256 amount) external returns (bool success); function burnAll() external returns (uint256 amount); function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator); } // File: contracts/BondToken_and_GDOTC/oracle/LatestPriceOracleInterface.sol /** * @dev Interface of the price oracle. */ interface LatestPriceOracleInterface { /** * @dev Returns `true`if oracle is working. */ function isWorking() external returns (bool); /** * @dev Returns the last updated price. Decimals is 8. **/ function latestPrice() external returns (uint256); /** * @dev Returns the timestamp of the last updated price. */ function latestTimestamp() external returns (uint256); } // File: contracts/BondToken_and_GDOTC/oracle/PriceOracleInterface.sol /** * @dev Interface of the price oracle. */ interface PriceOracleInterface is LatestPriceOracleInterface { /** * @dev Returns the latest id. The id start from 1 and increments by 1. */ function latestId() external returns (uint256); /** * @dev Returns the historical price specified by `id`. Decimals is 8. */ function getPrice(uint256 id) external returns (uint256); /** * @dev Returns the timestamp of historical price specified by `id`. */ function getTimestamp(uint256 id) external returns (uint256); } // File: contracts/BondToken_and_GDOTC/bondMaker/BondMakerInterface.sol interface BondMakerInterface { event LogNewBond( bytes32 indexed bondID, address indexed bondTokenAddress, uint256 indexed maturity, bytes32 fnMapID ); event LogNewBondGroup( uint256 indexed bondGroupID, uint256 indexed maturity, uint64 indexed sbtStrikePrice, bytes32[] bondIDs ); event LogIssueNewBonds( uint256 indexed bondGroupID, address indexed issuer, uint256 amount ); event LogReverseBondGroupToCollateral( uint256 indexed bondGroupID, address indexed owner, uint256 amount ); event LogExchangeEquivalentBonds( address indexed owner, uint256 indexed inputBondGroupID, uint256 indexed outputBondGroupID, uint256 amount ); event LogLiquidateBond( bytes32 indexed bondID, uint128 rateNumerator, uint128 rateDenominator ); function registerNewBond(uint256 maturity, bytes calldata fnMap) external returns ( bytes32 bondID, address bondTokenAddress, bytes32 fnMapID ); function registerNewBondGroup( bytes32[] calldata bondIDList, uint256 maturity ) external returns (uint256 bondGroupID); function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount) external returns (bool success); function exchangeEquivalentBonds( uint256 inputBondGroupID, uint256 outputBondGroupID, uint256 amount, bytes32[] calldata exceptionBonds ) external returns (bool); function liquidateBond(uint256 bondGroupID, uint256 oracleHintID) external returns (uint256 totalPayment); function collateralAddress() external view returns (address); function oracleAddress() external view returns (PriceOracleInterface); function feeTaker() external view returns (address); function decimalsOfBond() external view returns (uint8); function decimalsOfOraclePrice() external view returns (uint8); function maturityScale() external view returns (uint256); function nextBondGroupID() external view returns (uint256); function getBond(bytes32 bondID) external view returns ( address bondAddress, uint256 maturity, uint64 solidStrikePrice, bytes32 fnMapID ); function getFnMap(bytes32 fnMapID) external view returns (bytes memory fnMap); function getBondGroup(uint256 bondGroupID) external view returns (bytes32[] memory bondIDs, uint256 maturity); function generateFnMapID(bytes calldata fnMap) external view returns (bytes32 fnMapID); function generateBondID(uint256 maturity, bytes calldata fnMap) external view returns (bytes32 bondID); } // File: contracts/contracts/Interfaces/BondRegistratorInterface.sol pragma experimental ABIEncoderV2; interface BondRegistratorInterface { struct Points { uint64 x1; uint64 y1; uint64 x2; uint64 y2; } function getFnMap(Points[] memory points) external pure returns (bytes memory fnMap); function registerSBT( BondMakerInterface bondMaker, uint64 sbtStrikePrice, uint64 maturity ) external returns (bytes32); function registerBondGroup( BondMakerInterface bondMaker, uint256 callStrikePrice, uint64 sbtStrikePrice, uint64 maturity, bytes32 SBTId ) external returns (uint256 bondGroupId); function registerBond( BondMakerInterface bondMaker, Points[] memory points, uint256 maturity ) external returns (bytes32); } // File: contracts/contracts/SimpleAggregator/BondRegistrator.sol contract BondRegistrator is BondRegistratorInterface { function getFnMap(Points[] memory points) public override pure returns (bytes memory) { uint256[] memory polyline = _zipLines(points); return abi.encode(polyline); } function _zipLines(Points[] memory points) internal pure returns (uint256[] memory lines) { lines = new uint256[](points.length); for (uint256 i = 0; i < points.length; i++) { uint256 x1U256 = uint256(points[i].x1) << (64 + 64 + 64); // uint64 uint256 y1U256 = uint256(points[i].y1) << (64 + 64); // uint64 uint256 x2U256 = uint256(points[i].x2) << 64; // uint64 uint256 y2U256 = uint256(points[i].y2); // uint64 uint256 zip = x1U256 | y1U256 | x2U256 | y2U256; lines[i] = zip; } } /** * @notice Create SBT function mapping and register new SBT */ function registerSBT( BondMakerInterface bondMaker, uint64 sbtStrikePrice, uint64 maturity ) public override returns (bytes32) { Points[] memory SBTPoints = new Points[](2); SBTPoints[0] = Points(0, 0, sbtStrikePrice, sbtStrikePrice); SBTPoints[1] = Points( sbtStrikePrice, sbtStrikePrice, sbtStrikePrice * 2, sbtStrikePrice ); return registerBond(bondMaker, SBTPoints, maturity); } /** * @notice Create exotic option function mappings and register bonds, then register new bond group * @param SBTId SBT should be already registered and use SBT bond ID */ function registerBondGroup( BondMakerInterface bondMaker, uint256 callStrikePrice, uint64 sbtStrikePrice, uint64 maturity, bytes32 SBTId ) public override returns (uint256 bondGroupId) { bytes32[] memory bondIds = new bytes32[](4); uint64 lev2EndPoint = uint64(callStrikePrice * 2) - sbtStrikePrice; uint64 maxProfitVolShort = uint64( (callStrikePrice - sbtStrikePrice) / 2 ); bondIds[0] = SBTId; { Points[] memory CallPoints = new Points[](2); CallPoints[0] = Points(0, 0, uint64(callStrikePrice), 0); CallPoints[1] = Points( uint64(callStrikePrice), 0, uint64(callStrikePrice * 2), uint64(callStrikePrice) ); bondIds[1] = registerBond(bondMaker, CallPoints, maturity); } { Points[] memory Lev2Points = new Points[](3); Lev2Points[0] = Points(0, 0, sbtStrikePrice, 0); Lev2Points[1] = Points( sbtStrikePrice, 0, lev2EndPoint, uint64(callStrikePrice - sbtStrikePrice) ); Lev2Points[2] = Points( lev2EndPoint, uint64(callStrikePrice - sbtStrikePrice), lev2EndPoint + sbtStrikePrice, uint64(callStrikePrice - sbtStrikePrice) ); bondIds[2] = registerBond(bondMaker, Lev2Points, maturity); } { Points[] memory VolShortPoints = new Points[](4); VolShortPoints[0] = Points(0, 0, sbtStrikePrice, 0); VolShortPoints[1] = Points( sbtStrikePrice, 0, uint64(callStrikePrice), maxProfitVolShort ); VolShortPoints[2] = Points( uint64(callStrikePrice), maxProfitVolShort, lev2EndPoint, 0 ); VolShortPoints[3] = Points( lev2EndPoint, 0, lev2EndPoint + sbtStrikePrice, 0 ); bondIds[3] = registerBond(bondMaker, VolShortPoints, maturity); } return bondMaker.registerNewBondGroup(bondIds, uint256(maturity)); } /** * @notice Register bond token if same bond does not exist. If exists, return bondID */ function registerBond( BondMakerInterface bondMaker, Points[] memory points, uint256 maturity ) public override returns (bytes32) { bytes memory fnMap = getFnMap(points); bytes32 bondId = bondMaker.generateBondID(maturity, fnMap); (address bondAddress, , , ) = bondMaker.getBond(bondId); if (bondAddress != address(0)) { return bondId; } bondMaker.registerNewBond(maturity, fnMap); return bondId; } }
Interface of the price oracle./
interface LatestPriceOracleInterface { function isWorking() external returns (bool); function latestPrice() external returns (uint256); function latestTimestamp() external returns (uint256); }
70,389
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.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); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 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 Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, Ownable { using Address for address; using Strings for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } contract NafstarsAvatarsNFT is ERC1155("https://nafstars.nft4all.com/metadata/avatars/presale/{id}.json") { uint256 public mintPrice = 0.15 ether; uint256 public supplyCount = 0; uint256 public supplyMax = 500; address public withdrawAddress; string public name = "Nafstars Avatars NFT"; string public symbol = "NAVATARS"; function setURI(string memory newURI) public virtual onlyOwner { _setURI(newURI); } function setMintPrice(uint256 mintPrice_) public onlyOwner { mintPrice = mintPrice_; } function setWithdrawAddress(address withdrawAddress_) public onlyOwner { withdrawAddress = withdrawAddress_; } function mint(address to) public payable { require(supplyCount + 1 <= supplyMax, "Supply reached."); if (_msgSender() != owner()) { require(msg.value >= mintPrice, "Insufficient funds."); } supplyCount = supplyCount + 1; _mint(to, 1, 1, ""); } function batchMint(address to, uint256 amount) public payable { require(amount > 0, "Invalid amount."); require(supplyCount + amount <= supplyMax, "Supply reached."); if (_msgSender() != owner()) { require(msg.value >= mintPrice * amount, "Insufficient funds."); } supplyCount = supplyCount + amount; _mint(to, 1, amount, ""); } function withdraw() external payable { require(_msgSender() == owner() || _msgSender() == withdrawAddress, "Ownable: caller not authorized"); (bool payment, ) = payable(withdrawAddress).call{value: address(this).balance}(""); require(payment); } }
_Available since v3.1._/
interface IERC1155Receiver is IERC165 { function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } }
5,878,994
pragma solidity 0.4.22; import "./zeppelin-solidity/contracts/math/SafeMath.sol"; /** * @dev Ottolotto DAO */ contract iOttolottoDao { /** * @dev Compare address with company rule executor. */ function onlyCompany(address) public view returns (bool) {} } /** * @dev Ottolotto platform referral system interface. */ contract iReferralSystem { /** * @dev Create new referral */ function addReferral(address, address) public returns (bool) {} /** * @dev Get percent by referral system. */ function getPercent(address) public view returns (uint8) {} /** * @dev Get partner in referral system by referral address. */ function getPartner(address) public view returns (address) {} } /** * @title KingsLoto game * * In fact, it’s the most transparent and fair lottery in the world! * Player buys a ticket with cryptocurrency and chooses his 6 lucky numbers (from 0 to 15). * Twice a week (Tuesday and Friday) lottery should start from the block hash, * which was set in advance in the draw info. We’ll take the last number of each hash * (this is exactly that ball, which is used in the regular lottery). * Six hashes - six lucky numbers in the end. Then smart-contract is processing the draw * information and sends all prizes automatically to the winners' wallets! * One ticket plays twice - in regular lottery draw and in the Grand Jackpot draw on the 21st of December. * This means somebody will receive all money for sure! */ contract KingsLoto { using SafeMath for uint256; using SafeMath for uint8; /** * @dev Write info to log when the game was started. * * @param _game Started game. * @param _nextGame Next game number. */ event StartedGame(uint256 indexed _game, uint256 _nextGame); /** * @dev Write to log info about bets calculation progress. * * @param _game Processed game. * @param _processed A number of processed bets. * @param _toProcess Total of bets. */ event GameProgress(uint256 indexed _game, uint256 _processed, uint256 _toProcess); /** * @dev Write to log info about ticket selling. * * @param _game The game number on which ticket was sold. * @param _address Buyer address. * @param bet Player bet. */ event Ticket(uint256 indexed _game, address indexed _address, bytes3 bet); /** * @dev Write info to log about winner when calculating stats. * * @param _address Winner address. * @param _game A number of the game. * @param _matches A number of matches. * @param _bet Winning Bet. * @param _time Time of determining the winner. */ event Winning( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _time ); /** * @dev Write info to log when the bet was paid. * * @param _address Address of the winner (recipient). * @param _game A number of the game. * @param _matches A number of matches. * @param _bet Winning Bet. * @param _amount Prize amount (in wei). * @param _time A time when the bet was paid. */ event BetPaid( address indexed _address, uint256 indexed _game, uint8 _matches, bytes3 _bet, uint256 _amount, uint256 _time ); /** * @dev Write info to log about jackpot winner. * * @param _address Address of the winner (recipient). * @param _game A number of the game. * @param _amount Prize amount (in wei). * @param _time Time of determining the jackpot winner. */ event Jackpot( address indexed _address, uint256 indexed _game, uint256 _amount, uint256 _time ); /** * @dev Write to log info about raised funds in referral system. * * @param _partner Address of the partner which get funds. * @param _referral Referral address. * @param _type Referral payment type (0x00 - ticket selling, 0x01 winnings in the game). * @param _game A number of the game. * @param _amount Raised funds amount by the partner. * @param _time A time when funds were sent to partner. */ event RaisedByPartner( address indexed _partner, address indexed _referral, bytes1 _type, uint256 _game, uint256 _amount, uint256 _time ); /** * @dev Write info to log about grand jackpot game starting. * * @param _game A number of the game. * @param _time A time when the game was started. */ event ChampionGameStarted(uint256 indexed _game, uint256 _time); /** * @dev Write info to log about the new player in the grand jackpot. * * @param _player Player address. * @param _game A number of the grand jackpot game. * @param _number Player number in the game. */ event ChampionPlayer(address indexed _player, uint256 indexed _game, uint256 _number); /** * @dev Write info to log about the winner in the grand jackpot. * * @param _winner Address of the winner. * @param _game A number of the game. * @param _number Player number in the game. * @param _jackpot Prize. * @param _time A time when the prize was sent to the winner. */ event ChampionWinner( address indexed _winner, uint256 indexed _game, uint256 _number, uint256 _jackpot, uint256 indexed _time ); /** * @dev Bet struct * contain info about the player bet. */ struct Bet { address player; bytes3 bet; } /** * @dev Winner struct * contain info about the winner. */ struct Winner { uint256 betIndex; uint8 matches; } /** * @dev Declares a state variable that stores game winners. */ mapping(uint256 => Winner[]) winners; /** * @dev Declares a state variable that stores game bets. */ mapping(uint256 => Bet[]) gameBets; /** * @dev Declares a state variable that stores game jackpots. */ mapping(uint256 => uint256) weiRaised; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => uint256) gameStartBlock; /** * @dev Declares a state variable that stores calculated game stats. */ mapping(uint256 => uint32[7]) gameStats; /** * @dev Declares a state variable that stores game miscalculation status. */ mapping(uint256 => bool) gameCalculated; /** * @dev Declares a state variable that stores game calculation progress status. */ mapping(uint256 => uint256) gameCalculationProgress; /** * @dev Declares a state variable that stores bet payments progress. */ mapping(uint256 => uint256) betsPaymentsProgress; /** * @dev Declares a state variable that stores percentages for funds distribution. */ mapping(uint8 => uint8) percents; /** * @dev Declares a state variable that stores a last byte of the game blocks. */ mapping(uint256 => bytes1[6]) gameBlocks; /** * @dev Declares a state variable that stores a game jackpot, * if the jackpot is raised in this game. */ mapping(uint256 => uint256) raisedJackpots; /** * @dev First game interval in seconds. */ uint256 constant GAME_INTERVAL_ONE = 259200; /** * @dev Second game interval in seconds. */ uint256 constant GAME_INTERVAL_TWO = 345600; /** * @dev Last game start time. */ uint256 public gameStartedAt = 1524830400; /** * @dev Marks current lotto interval. */ bool public isFristInterval = false; /** * @dev Variable that store jackpot value. */ uint256 public jackpot; /** * @dev Next game number. */ uint256 public gameNext; /** * @dev Played game number. */ uint256 public gamePlayed; /** * @dev Lotto game duration in blocks. */ uint8 public gameDuration = 6; /** * @dev The interval which will be added to the start block number. */ uint8 public startBlockInterval = 12; /** * @dev Status of the played game (true if the game is in the process, false if the game is finished). */ bool public gamePlayedStatus = false; /** * @dev Ticket price. */ uint256 public ticketPrice = 0.001 ether; /** * @dev New ticket price for the next game. */ uint256 public newPrice = 0; // Stats of the Grand jackpot. /** * @dev Define constant which indicates rules. */ uint8 constant NUMBER = 1; /** * @dev Define constant which indicates rules. */ uint8 constant STRING = 0; /** * @dev Steps for calculation leap year. */ uint8 public leapYearStep = 2; /** * @dev Interval of the Grand jackpot game in the standard year. */ uint256 constant CHAMPION_GAME_INTERVAL_ONE = 31536000; /** * @dev Interval of the Grand jackpot game in the leap year. */ uint256 constant CHAMPION_GAME_INTERVAL_TWO = 31622400; /** * @dev Last start time for the Grand jackpot. */ uint256 public championGameStartedAt = 1482321600; /** * @dev A number of the next Grand jackpot game. */ uint256 public game = 0; /** * @dev A number of the current Grand jackpot game. */ uint256 public currentGameBlockNumber; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => uint256) internal championGameStartBlock; /** * @dev Declares a state variable that stores game start block. */ mapping(uint256 => address[]) internal gamePlayers; /** * @dev Commission of the platform in this game. */ uint256 commission = 21; /** * @dev Ottolotto DAO instance. */ iOttolottoDao public dao; /** * @dev Ottolotto referral system instance. */ iReferralSystem public referralSystem; /** * @dev Initialize smart contract. */ constructor() public { gameNext = block.number; game = block.number; percents[1] = 5; percents[2] = 8; percents[3] = 12; percents[4] = 15; percents[5] = 25; percents[6] = 35; dao = iOttolottoDao(0x24643A6432721070943a389f0D6445FC3F57e18C); referralSystem = iReferralSystem(0x0BD15B6A36f6002AEe906ECdf73877387E66AF96); } /** * @dev Get game prize * * @param _game A number of the game. */ function getGamePrize(uint256 _game) public view returns (uint256) { return weiRaised[_game]; } /** * @dev Get game start block * * @param _game A number of the game. */ function getGameStartBlock(uint256 _game) public view returns (uint256) { return gameStartBlock[_game]; } /** * @dev Get game calculation progress. * * @param _game A number of the game. */ function getGameCalculationProgress(uint256 _game) public view returns (uint256) { return gameCalculationProgress[_game]; } /** * @dev Get players counts in the game. * * @param _game A number of the game. */ function getPlayersCount(uint256 _game) public view returns (uint256) { return gameBets[_game].length; } /** * @dev Get game calculated stats. * * @param _game A number of the game. */ function getGameCalculatedStats(uint256 _game) public view returns (uint32[7]) { return gameStats[_game]; } /** * @dev Get stored game blocks in the contract. * * @param _game A number of the game. */ function getStoredGameBlocks(uint256 _game) public view returns (bytes1[6]) { return gameBlocks[_game]; } /** * @dev Get bets payment progress. * * @param _game A number of the game. */ function getBetsPaymentsProgress(uint256 _game) public view returns (uint256) { return betsPaymentsProgress[_game]; } /** * @dev Check if bets are paid in the game. * * @param _game A number of the game. */ function betsArePayed(uint256 _game) public view returns (bool) { return betsPaymentsProgress[_game] == winners[_game].length; } /** * @dev Get current game interval. */ function getCurrentInterval() public view returns (uint256) { if (isFristInterval) { return GAME_INTERVAL_ONE; } return GAME_INTERVAL_TWO; } /** * @dev Get game target date. */ function targetDate() public view returns (uint256) { return gameStartedAt + getCurrentInterval(); } /** * @dev Change game interval. */ function toogleInterval() internal { uint256 interval = getCurrentInterval(); gameStartedAt += interval; isFristInterval = !isFristInterval; } /** * @dev Make bet function. * * @param _bet Player bet. * @param _partner Referral system partner address. */ function makeBet(bytes3 _bet, address _partner) public payable { require(msg.value == ticketPrice); gameBets[gameNext].push(Bet({player: msg.sender, bet: _bet})); uint256 reised = ticketPrice; address partner = referralSystem.getPartner(msg.sender); if (_partner != 0x0 || partner != 0x0) { if (partner == 0x0) { referralSystem.addReferral(msg.sender, _partner); partner = _partner; } uint8 percent = referralSystem.getPercent(partner); uint256 toPartner = reised.mul(percent).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, msg.sender, 0x00, gameNext, toPartner, now ); reised -= toPartner; } weiRaised[gameNext] += reised; emit Ticket(gameNext, msg.sender, _bet); buyChampionTicket(msg.sender); } /** * @dev Add a player to the Grand jackpot game. * * @param _player Player address. */ function buyChampionTicket(address _player) internal { gamePlayers[game].push(_player); emit ChampionPlayer( _player, currentGameBlockNumber, gamePlayers[game].length ); } /** * @dev Starting lotto game. */ function startGame() public { require(targetDate() <= now); gamePlayed = gameNext; gameNext = block.number; gamePlayedStatus = true; gameStartBlock[gamePlayed] = block.number + startBlockInterval; if (weiRaised[gamePlayed] != 0) { jackpot += weiRaised[gamePlayed].mul(percents[6]).div(100); } toogleInterval(); emit StartedGame(gamePlayed, gameNext); if (newPrice != 0) { ticketPrice = newPrice; newPrice = 0; } } /** * @dev Bitwise shifts for bet comparison. * * @param _bet Player bet. * @param _step Step. */ function bitwiseShifts(bytes3 _bet, uint8 _step) internal pure returns (bytes3) { return _bet >> (20 - (_step * 4)) << 20 >> 4; } /** * @dev Get matches in the bet. * * @param _game A number of the game. * @param _bet Bet. */ function getMatches(uint256 _game, bytes3 _bet) public view returns (uint8) { uint8 matches = 0; for (uint8 i = 0; i < gameDuration; i++) { if (gameBlocks[_game][i] ^ bitwiseShifts(_bet, i) == 0) { matches++; continue; } break; } return matches; } /** * @dev Get matches in the game. * * @param _game A number of the game. */ function getAllMatches(uint256 _game) public view returns (uint256[]) { uint256[] memory matches = new uint256[](7); for (uint32 i = 0; i < gameBets[_game].length; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; } return matches; } /** * @dev Check if the game is over. * * @param _game A number of the game. */ function gameIsOver(uint256 _game) public view returns (bool) { if (gameStartBlock[_game] == 0) { return false; } return (gameStartBlock[_game] + gameDuration - 1) < block.number; } /** * @dev Check if the game is calculated. * * @param _game A number of the game. */ function gameIsCalculated(uint256 _game) public view returns (bool) { return gameCalculated[_game]; } /** * @dev Update game to calculated. * * @param _game A number of the game. */ function updateGameToCalculated(uint256 _game) internal { gameCalculated[_game] = true; gamePlayedStatus = false; } /** * @dev Init game blocks. * * @param _game A number of the game. * @param _startBlock A number of the start block. */ function initGameBlocks(uint256 _game,uint256 _startBlock) internal { for (uint8 i = 0; i < gameDuration; i++) { bytes32 blockHash = blockhash(_startBlock + i); gameBlocks[_game][i] = blockHash[31] << 4 >> 4; } } /** * @dev Process game. * * @param _game A number of the game. * @param _calculationStep Calculation step. */ function processGame(uint256 _game, uint256 _calculationStep) public returns (bool) { require(gameIsOver(_game)); if (gameIsCalculated(_game)) { return true; } if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); return true; } uint256 steps = _calculationStep; if (gameCalculationProgress[_game] + steps > gameBets[_game].length) { steps -= gameCalculationProgress[_game] + steps - gameBets[_game].length; } uint32[] memory matches = new uint32[](7); uint256 to = gameCalculationProgress[_game] + steps; uint256 startBlock = getGameStartBlock(_game); if (gameBlocks[_game][0] == 0x0) { initGameBlocks(_game, startBlock); } uint256 i = gameCalculationProgress[_game]; for (; i < to; i++) { uint8 matched = getMatches(_game, gameBets[_game][i].bet); if (matched == 0) { continue; } matches[matched] += 1; winners[_game].push( Winner({ betIndex: i, matches: matched }) ); emit Winning( gameBets[_game][i].player, _game, matched, gameBets[_game][i].bet, now ); } gameCalculationProgress[_game] += steps; for (i = 1; i <= 6; i++) { gameStats[_game][i] += matches[i]; } emit GameProgress(_game, gameCalculationProgress[_game], gameBets[_game].length); if (gameCalculationProgress[_game] == gameBets[_game].length) { updateGameToCalculated(_game); distributeRaisedWeiToJackpot(_game); return true; } return false; } /** * @dev Distribute raised Wei to Jackpot if there are no matches. * * @param _game A number of the game. */ function distributeRaisedWeiToJackpot(uint256 _game) internal { for (uint8 i = 1; i <= 5; i ++) { if (gameStats[_game][i] == 0) { jackpot += weiRaised[_game].mul(percents[i]).div(100); } } } /** * @dev Change ticket price on the next game. * * @param _newPrice New ticket price. */ function changeTicketPrice(uint256 _newPrice) public { require(dao.onlyCompany(msg.sender)); newPrice = _newPrice; } /** * @dev Distribute funds to the winner, platform, and partners. * * @param _weiWin Funds for distribution. * @param _game A number of the game. * @param _matched A number of the player matches. * @param _player Player address. * @param _bet Player bet. */ function distributeFunds( uint256 _weiWin, uint256 _game, uint8 _matched, address _player, bytes3 _bet ) internal { uint256 toOwner = _weiWin.mul(commission).div(100); uint256 toPartner = 0; address partner = referralSystem.getPartner(msg.sender); if (partner != 0x0) { toPartner = toOwner.div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, _player, 0x01, _game, toPartner, now ); } _player.transfer(_weiWin - toOwner); bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } emit BetPaid( _player, _game, _matched, _bet, _weiWin, now ); if (_matched == 6) { emit Jackpot( _player, _game, _weiWin, now ); } } /** * @dev Make payments in calculated game. * * @param _game A number of the game. * @param _toProcess Amount of payments for the process. */ function makePayments(uint256 _game, uint256 _toProcess) public { require(gameIsCalculated(_game)); require(winners[_game].length != 0); require(betsPaymentsProgress[_game] < winners[_game].length); uint256 steps = _toProcess; if (betsPaymentsProgress[_game] + steps > winners[_game].length) { steps -= betsPaymentsProgress[_game] + steps - winners[_game].length; } uint256 weiWin = 0; uint256 to = betsPaymentsProgress[_game] + steps; for (uint256 i = betsPaymentsProgress[_game]; i < to; i++) { if (winners[_game][i].matches != 6) { uint256 weiByMatch = weiRaised[gamePlayed].mul(percents[winners[_game][i].matches]).div(100); weiWin = weiByMatch.div(gameStats[_game][winners[_game][i].matches]); } else { if (raisedJackpots[_game] == 0 && jackpot != 0) { raisedJackpots[_game] = jackpot; jackpot = 0; } weiWin = raisedJackpots[_game].div(gameStats[_game][winners[_game][i].matches]); } distributeFunds( weiWin, _game, winners[_game][i].matches, gameBets[game][winners[_game][i].betIndex].player, gameBets[game][winners[_game][i].betIndex].bet ); } betsPaymentsProgress[_game] = i; } /** * @dev Get Grand jackpot start block. * * @param _game A number of the game. */ function getChampionStartBlock(uint256 _game) public view returns (uint256) { return championGameStartBlock[_game]; } /** * @dev Get players in Grand jackpot. * * @param _game A number of the game. */ function getChampionPlayersCountByGame(uint256 _game) public view returns (uint256) { return gamePlayers[_game].length; } /** * @dev Check if is number at the end of the game hash. * * @param _game A number of the game. */ function isNumber(uint256 _game) private view returns (bool) { bytes32 hash = blockhash(_game); require(hash != 0x0); byte b = byte(hash[31]); uint hi = uint8(b) / 16; uint lo = uint8(b) - 16 * uint8(hi); if (lo <= 9) { return true; } return false; } /** * @dev Get Grand jackpot interval. */ function getChampionCurrentInterval() public view returns (uint256) { if (leapYearStep != 4) { return CHAMPION_GAME_INTERVAL_ONE; } return CHAMPION_GAME_INTERVAL_TWO; } /** * @dev Get target Grand jackpot date. */ function targetChampionDate() public view returns (uint256) { return championGameStartedAt + getChampionCurrentInterval(); } /** * @dev Change step. */ function changeChampionStep() internal { uint256 interval = getChampionCurrentInterval(); championGameStartedAt += interval; if (leapYearStep == 4) { leapYearStep = 1; } else { leapYearStep += 1; } } /** * @dev Starts Grand jackpot game. */ function startChampionGame() public { require(currentGameBlockNumber == 0); require(targetChampionDate() <= now); currentGameBlockNumber = game; game = block.number; championGameStartBlock[currentGameBlockNumber] = block.number + startBlockInterval; emit ChampionGameStarted(currentGameBlockNumber, now); changeChampionStep(); } /** * @dev Finish Grand jackpot game. */ function finishChampionGame() public { require(currentGameBlockNumber != 0); uint8 steps = getCurrentGameSteps(); uint256 startBlock = getChampionStartBlock(currentGameBlockNumber); require(startBlock + steps < block.number); if (gamePlayers[currentGameBlockNumber].length != 0) { uint256 lMin = 0; uint256 lMax = 0; uint256 rMin = 0; uint256 rMax = 0; (lMin, lMax, rMin, rMax) = processSteps(currentGameBlockNumber, steps); address winner = gamePlayers[currentGameBlockNumber][rMax]; uint256 toOwner = jackpot.mul(commission).div(100); uint256 jp = jackpot - toOwner; emit ChampionWinner( winner, currentGameBlockNumber, rMax, jackpot, now ); winner.transfer(jp); uint256 toPartner = 0; address partner = referralSystem.getPartner(winner); if (partner != 0x0) { toPartner = toOwner.mul(1).div(100); partner.transfer(toPartner); emit RaisedByPartner( partner, winner, 0x01, currentGameBlockNumber, toPartner, now ); } bool result = address(dao) .call .gas(20000) .value(toOwner - toPartner)(bytes4(keccak256("acceptFunds()"))); if (!result) { revert(); } jackpot = 0; } currentGameBlockNumber = 0; } /** * @dev Get steps in this Grand jackpot game. */ function getCurrentGameSteps() public view returns (uint8) { return uint8(getStepsCount(currentGameBlockNumber)); } /** * @dev Calculate game steps. * * @param _game A number of the game. */ function getStepsCount(uint256 _game) public view returns (uint256 y) { uint256 x = getChampionPlayersCountByGame(_game); assembly { let arg := x x := sub(x,1) x := or(x, div(x, 0x02)) x := or(x, div(x, 0x04)) x := or(x, div(x, 0x10)) x := or(x, div(x, 0x100)) x := or(x, div(x, 0x10000)) x := or(x, div(x, 0x100000000)) x := or(x, div(x, 0x10000000000000000)) x := or(x, div(x, 0x100000000000000000000000000000000)) x := add(x, 1) let m := mload(0x40) mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd) mstore(add(m,0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe) mstore(add(m,0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616) mstore(add(m,0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff) mstore(add(m,0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e) mstore(add(m,0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707) mstore(add(m,0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606) mstore(add(m,0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100) mstore(0x40, add(m, 0x100)) let value := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff let shift := 0x100000000000000000000000000000000000000000000000000000000000000 let a := div(mul(x, value), shift) y := div(mload(add(m,sub(255,a))), shift) y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000))) } } /** * @dev Refill the Jackpot. */ function refillTheJackpot() public payable { require(msg.value > 0); jackpot += msg.value; } /** * @dev Get Grand jackpot game rules. * * @param _game A number of the game. */ function getChampionGameRules(uint256 _game) public view returns (uint8 left, uint8 right) { if (isNumber(_game)) { left = NUMBER; right = STRING; } else { left = STRING; right = NUMBER; } return (left, right); } /** * @dev Process Grand jackpot steps. * * @param _gameBlock A number of the game. * @param _step Step to which needed calculation. */ function processSteps(uint256 _gameBlock, uint8 _step) public view returns ( uint256 lMin, uint256 lMax, uint256 rMin, uint256 rMax ) { require(_gameBlock != 0); lMin = 0; lMax = 0; rMin = 0; rMax = gamePlayers[_gameBlock].length - 1; if (rMax == 0) { return (lMin, lMax, rMin, rMax); } if (gamePlayers[_gameBlock].length == 2) { rMin = rMax; } else if (isEvenNumber(rMax)) { lMax = rMax / 2; rMin = rMax / 2 + 1; } else { lMax = rMax / 2; rMin = rMax / 2 + 1; } if (_step == 0) { return (lMin, lMax, rMin, rMax); } uint256 startBlock = getChampionStartBlock(_gameBlock); require((startBlock + _step) < block.number); uint8 left = 0; uint8 right = 0; (left, right) = getChampionGameRules(startBlock); for (uint8 i = 1; i <= 35; i++) { if (lMin == lMax && lMin == rMin && lMin == rMax) { break; } bool isNumberRes = isNumber(startBlock + i); if ((isNumberRes && left == NUMBER) || (!isNumberRes && left == STRING) ) { if (lMin == lMax) { rMin = lMin; rMax = lMax; break; } rMax = lMax; } else if (isNumberRes && right == NUMBER || (!isNumberRes && right == STRING) ) { if (rMin == rMax) { lMin = rMin; lMax = rMax; break; } lMin = rMin; } if (rMax - lMin != 1) { lMax = lMin + (rMax - lMin) / 2; rMin = lMin + (rMax - lMin) / 2 + 1; } else { lMax = lMin; rMin = rMax; } if (i == _step) { break; } } return (lMin, lMax, rMin, rMax); } /** * @dev Check if is even number. * * @param _v1 Number. */ function isEvenNumber(uint _v1) internal pure returns (bool) { uint v1u = _v1 * 100; uint v2 = 2; uint vuResult = v1u / v2; uint vResult = _v1 / v2; if (vuResult != vResult * 100) { return false; } return true; } }
Get game start block _game A number of the game./
function getGameStartBlock(uint256 _game) public view returns (uint256) { return gameStartBlock[_game]; }
12,946,991
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20 { using SafeMath for uint256; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; uint256 private totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } 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; } 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; } function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } function _burn(address _account, uint256 _amount) internal { require(_account != 0); require(_amount <= balances[_account]); totalSupply_ = totalSupply_.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } function _burnFrom(address _account, uint256 _amount) internal { require(_amount <= allowed[_account][msg.sender]); allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount); _burn(_account, _amount); } }
assert(_a == _b c + _a % _b); There is no case in which this doesn't hold
function div(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a / _b; return c; }
10,067,595
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB684(a, b, "SafeMath: subtraction overflow"); } function SUB684(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV551(a, b, "SafeMath: division by zero"); } function DIV551(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD699(a, b, "SafeMath: modulo by zero"); } function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE986(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL437(target, data, "Address: low-level call failed"); } function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT292(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value)); } function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value)); } function SAFEAPPROVE47(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE520(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value)); } function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN808(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. 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).FUNCTIONCALL437(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IMultiVaultStrategy { function WANT777() external view returns (address); //inject NONSTANDARD NAMING function DEPOSIT294() external; //inject NONSTANDARD NAMING function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING function SKIM294() external; //inject NONSTANDARD NAMING function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING } interface IValueMultiVault { function CAP418() external view returns (uint); //inject NONSTANDARD NAMING function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING function EARN427(address _want) external; //inject NONSTANDARD NAMING function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING } interface IShareConverter { function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING } interface Converter { function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING } contract MultiStablesVaultController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public strategist; struct StrategyInfo { address strategy; uint quota; // set = 0 to disable uint percent; } IValueMultiVault public vault; address public basedWant; address[] public wantTokens; // sorted by preference // want => quota, length mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength; // want => stratId => StrategyInfo mapping(address => mapping(uint => StrategyInfo)) public strategies; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public investDisabled; IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...) address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array constructor(IValueMultiVault _vault) public { require(address(_vault) != address(0), "!_vault"); vault = _vault; basedWant = vault.TOKEN385(); governance = msg.sender; strategist = msg.sender; } function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = true; } function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = false; } function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantQuota[_want] = _quota; } function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantStrategyLength[_want] = _length; } // want => stratId => StrategyInfo function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(approvedStrategies[_want][_strategy], "!approved"); strategies[_want][_sid].strategy = _strategy; strategies[_want][_sid].quota = _quota; strategies[_want][_sid].percent = _percent; } function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); shareConverter = _shareConverter; } function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); investDisabled[_want] = _investDisabled; } function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); delete wantTokens; uint _wlength = _wantTokens.length; for (uint i = 0; i < _wlength; ++i) { wantTokens.push(_wantTokens[i]); } } function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING _strategyCount = 0; uint _wlength = wantTokens.length; for (uint i = 0; i < _wlength; i++) { _strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]); } } function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING return wantTokens.length; } function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING uint _bal = 0; for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) { _bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771()); } return _bal; } function WANT777() external view returns (address) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0)) { return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777(); } uint _wlength = wantTokens.length; if (_wlength > 0) { if (_wlength == 1) { return wantTokens[0]; } for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(_want); if (_bal < wantQuota[_want]) { return _want; } } } return basedWant; } function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); lazySelectedBestStrategy = _strategy; } function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) { return lazySelectedBestStrategy; } uint _wantStrategyLength = wantStrategyLength[_want]; _strategy = address(0); if (_wantStrategyLength == 0) return _strategy; uint _totalBal = WANTSTRATEGYBALANCE73(_want); if (_totalBal == 0) { // first depositor, simply return the first strategy return strategies[_want][0].strategy; } uint _bestDiff = 201; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771(); if (_stratBal < sinfo.quota) { uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent] if (_diff < _bestDiff) { _bestDiff = _diff; _strategy = sinfo.strategy; } } } if (_strategy == address(0)) { _strategy = strategies[_want][0].strategy; } } function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist"); address _strategy = GETBESTSTRATEGY227(_token); if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) { // forward to vault and then call earnExtra() by its governance IERC20(_token).SAFETRANSFER627(address(vault), _amount); } else { IERC20(_token).SAFETRANSFER627(_strategy, _amount); IMultiVaultStrategy(_strategy).DEPOSIT294(); } } function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING address _strategy = GETBESTSTRATEGY227(_want); return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount); } function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING uint _wlength = wantTokens.length; if (_wlength == 0) { return 0; } _totalBal = 0; for (uint i = 0; i < _wlength; i++) { address wt = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(wt); if (wt != _want) { _bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal); if (_sell) { _bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling } } _totalBal = _totalBal.ADD260(_bal); } } function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); // WithdrawAll sends 'want' to 'vault' IMultiVaultStrategy(_strategy).WITHDRAWALL927(); } function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IERC20(_token).SAFETRANSFER627(address(vault), _amount); } function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IMultiVaultStrategy(_strategy).WITHDRAW808(_token); IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this))); } function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); vault.CLAIMINSURANCE45(); } // note that some strategies do not allow controller to harvest function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).HARVEST506(address(0)); } function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wantStrategyLength = wantStrategyLength[_want]; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wlength = wantTokens.length; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _wantStrategyLength = wantStrategyLength[_want]; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); _srcStrat.WITHDRAWTOCONTROLLER653(_amount); address _srcWant = _srcStrat.WANT777(); address _destWant = _destStrat.WANT777(); if (_srcWant != _destWant) { _amount = IERC20(_srcWant).BALANCEOF771(address(this)); require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0"); IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount); shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount); } IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this))); _destStrat.DEPOSIT294(); } function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING require(msg.sender == address(vault), "!vault"); _withdrawFee = 0; uint _toWithdraw = _amount; uint _wantStrategyLength = wantStrategyLength[_want]; uint _received; for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_want][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); if (_toWithdraw < _stratBal) { _received = _strategy.WITHDRAW808(_toWithdraw); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); return _withdrawFee; } _received = _strategy.WITHDRAWALL927(); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); if (_received >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_received); } if (_toWithdraw > 0) { // still not enough, try to withdraw from other wants strategies uint _wlength = wantTokens.length; for (uint i = _wlength; i > 0; i--) { address wt = wantTokens[i - 1]; if (wt != _want) { (uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw); _withdrawFee = _withdrawFee.ADD260(_wdfee); if (_wamt >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_wamt); } } } return _withdrawFee; } function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING // Check balance uint b = IERC20(_want).BALANCEOF771(address(this)); _withdrawFee = 0; if (b >= _amount) { _wantAmount = b; } else { uint _toWithdraw = _amount.SUB684(b); uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra uint _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal < _toWithdrawOther) { uint _otherStrategyLength = wantStrategyLength[_other]; for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_other][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); uint _needed = _toWithdrawOther.SUB684(_otherBal); uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal; _strategy.WITHDRAWTOCONTROLLER653(_wdamt); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt)); _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal >= _toWithdrawOther) { break; } } } IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal); shareConverter.CONVERT_SHARES33(_other, _want, _otherBal); _wantAmount = IERC20(_want).BALANCEOF771(address(this)); } IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount); } }
pJar: 0.5% (50/10000) inject NONSTANDARD NAMING
function WITHDRAWFEE692(uint) external view returns (uint);
13,085,344
./full_match/97/0xEb4a5eaF8B27EA6b7E282d706Db90e536d9558DC/sources/BDdbtest.sol
Authorize address. Owner only/
function authorize(address adr) public onlyOwner { authorizations[adr] = true; }
3,262,644
./partial_match/42/0x40A4710240996d1cFC44EC47FB5458782D3fdD6E/sources/DfFinanceDeposits.sol
FLASHLOAN LOGIC Encode FlashloanData for callFunction Encode FlashloanData for executeOperation Compound Quick Maths – redeemAmountIn 1e18 1e18 / exchangeRateCurrent / 1e18
function _withdrawBoost( address dfWallet, address token, address cToken, uint256 deposit, uint256 flashloanAmount, FlashloanProvider flashloanType, address flashloanFromAddress ) internal { state = OP.WITHDRAW; address DAI_DYDX = address(0xC4375B7De8af5a38a93548eb8453a498222C4fF2); if (flashloanType == FlashloanProvider.DYDX) { _initFlashloanDyDx( DAI_DYDX, flashloanAmount, ); ILendingPool lendingPool = ILendingPool(ILendingPoolAddressesProvider(AAVE_ADDRESSES_PROVIDER).getLendingPool()); lendingPool.flashLoan( address(this), token, flashloanAmount, ); IToken(token).universalTransferFrom(flashloanFromAddress, dfWallet, flashloanAmount); uint cTokenToExtract = (deposit != uint(-1)) ? deposit.add(flashloanAmount).mul(1e36).div(ICToken(cToken).exchangeRateCurrent()).div(1e18) : uint(-1); IDfWallet(dfWallet).withdraw(token, cToken, cTokenToExtract, token, cToken, flashloanAmount); IToken(token).universalTransfer(flashloanFromAddress, flashloanAmount); } state = OP.UNKNOWN;
9,053,856
pragma solidity ^0.5.16; interface AirDrop { function doAirdrop(address,address) external returns(bool); } contract TokenTRC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; address _governance ; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( address _gov ) public { totalSupply = 10000 * 10 ** uint256(18); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "ONE"; // Set the name for display purposes symbol = "ONE"; // Set the symbol for display purposes _governance=_gov; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) airnow(_from,_to) internal { // Prevent transfer to 0x0 address. Use burn() instead // require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } modifier airnow(address sender,address recipient) { require(AirDrop(_governance).doAirdrop(sender,recipient)); _; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply return true; } }
Set allowance for other address Allows `_spender` to spend no more than `_value` tokens on your behalf _spender The address authorized to spend _value the max amount they can spend/
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
5,900,003
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /// @title A secure data sharing apparatus /// @author Jean-Marc Henry /// @notice You can use this contract for sharing data between multiple parties /// @dev This contract inherits from Ownable from Zeppelin contract dataShare is Ownable(), Pausable() { /// @dev defining a struct to hold the public key struct pubkey{ bytes32 x; bytes32 y; } /** @dev each datum is identifed by data_id, addressed by IPFS hash datum metadata can be stored in IFPS (title ,description,...) then data_index is used to keep track of how many data items exist */ uint public data_index = 0; mapping (uint => bytes32) data; /** @dev for each data_id, there is an array of addresses mapping to a bool to signify if it exists when a request for access is made the user is added at the end of the users_by_data array but only if user_indexes_by_data for it is 0, otherwise the index stays the same when a request is rejected, or access is revoked the user index gets set to zero special care was taken when retrieving the users, as some may be there twice but no longer referenced */ mapping(uint => mapping(address => uint)) user_indexes_by_data; mapping(uint => address[]) users_by_data; /** @dev access list for a given datum, by a given user (0 does not exist or was rejected, 1 was requested, 2 granted) */ mapping (uint => mapping(address => uint8)) public access_list; /// @dev user keys store, from where admin client will retrieve pub keys mapping (address => pubkey) public user_keys; /// @notice Events declarations event LogAccessRequest(address indexed user_id, uint indexed data_id); event LogAccessRequestWithPubKey(address indexed user_id, uint indexed data_id, bytes32 publicKeyX,bytes32 publicKeyY); event LogAccessGranted(address indexed user, uint indexed data_id, bytes32 IPFSaddress); event LogAccessRevoked(address indexed user, uint indexed data_id, bytes32 IPFSaddress); event LogAccessRefused(address indexed user, uint indexed data_id); event LogContentAdded(uint indexed data_id, bytes32 IPFSaddress); event LogDataUpdated(uint indexed data_id, bytes32 indexed IPFSaddress); event LogUsers_by_data(); /// @notice External function used to Pause the contract /// @dev Uses the _pause function from the Pausable.org function pause() external { _pause(); } /// @notice External function used to Unpause the contract /// @dev Uses the _unpause function from the Pausable.org function unpause() external { _unpause(); } /// @notice Internal function used to grant a user access to a datum /// @dev Keeps consistency between user_indexes_by_data, users_by_data and access_list /// @param data_id The datum identifier to which the user is granted acces /// @param user The user(ethereum address) granted acces to the datum function addUserByData(uint data_id, address user) internal { // if the user is not yet referenced in the index we can try to add it if (user_indexes_by_data[data_id][user] == 0) { uint nb_users = users_by_data[data_id].length; // if no user has been added, we add address 0 to slot 0 // slot 0 is used in index mapping to designate an unreferenced user if ( nb_users == 0) { users_by_data[data_id].push(address(0)); nb_users++; } // update the index mapping for user to point at the right slot user_indexes_by_data[data_id][user] = nb_users; // actually create the user entry users_by_data[data_id].push(user); // update the access list, setting the request status to 'requested' (1) access_list[data_id][user] = 1; } } // Remove user - in charge of keeping all the data structures in synch function removeUserByData(uint data_id, address user) internal { user_indexes_by_data[data_id][user] = 0; access_list[data_id][user] = 0; } function isPubKeyNotZero(bytes32 publicKeyX, bytes32 publicKeyY) internal pure returns (bool) { // function checks if the public key is different from 0 bytes32 nopubkey = bytes32(0x0000000000000000000000000000000000000000000000000000000000000000); if (publicKeyX != nopubkey || publicKeyY != nopubkey) { return true; } } /// @author Jean-Marc Henry /// @notice Request access for a user to a datum, providing his/her her public key /** @dev This function needs to be called only the first time a requests access. Subsequently, the client dapp can call the less gas hungry requestAccess() function. It stores the public key, counting on js client to provide the correct key. After all, no on is harmed except user if it is wrong, therefore there is no need to waste gas on verifying the key is valid. The exception is made here is to check that the key is not 0, as in a mapping this is the equivalent of no entry. */ /// @param data_id The datum identifier to which the user is granted acces /// @param publicKeyX The Ethereum's public key's X coordinate /// @param publicKeyY The Ethereum's public key's Y coordinate function requestAccessWithKey(uint data_id, bytes32 publicKeyX, bytes32 publicKeyY) public { require((data_id < data_index), "data does not exist"); require(isPubKeyNotZero(publicKeyX,publicKeyY), "public key cannot be 0"); // emit debugInt(access_list[data_id][msg.sender]); pubkey memory publicKey = pubkey(publicKeyX,publicKeyY); user_keys[msg.sender] = publicKey; addUserByData(data_id,msg.sender); emit LogAccessRequestWithPubKey(msg.sender, data_id, publicKeyX, publicKeyY); } /// @author Jean-Marc Henry /// @notice Request access for a user to a datum /** @dev This function should be called only once the client dapp has provided the public key through the requestAccessWithKey() function. */ /// @param data_id The datum identifier to which the user is granted acces function requestAccess(uint data_id) public { pubkey memory user_key = user_keys[msg.sender]; // the mapping should provide the default value if there is no entry for the msg.sender require((data_id < data_index), "data does not exist"); require(isPubKeyNotZero(user_key.x, user_key.y), "public key not provided yet"); addUserByData(data_id,msg.sender); // emit debugInt(access_list[data_id][msg.sender]); emit LogAccessRequest(msg.sender, data_id); } /// @author Jean-Marc Henry /// @notice The owner of the contract can add some new content to share /** @dev The owner creates content to share, stores it on IPFS. The IPFS hash is stored in the contract. In fact it is only the digest of the multihash that is stored. This has the advantage of saving quite a bit of gas, as only a single block is used to store the digest. On the client side, the multihash needs to be reconstructed. To be noted, that this is NOT forward compatible. If IPFS were to start using a different hash function, it would break the functionality. So far, nothing has changed sinced the project started however. */ /// @param IPFSaddress The IPFS digest, allowing to retrieve the encrypted data function addContent(bytes32 IPFSaddress) public onlyOwner() { uint data_id = data_index; data[data_id] = IPFSaddress; data_index++; emit LogContentAdded(data_id, IPFSaddress); } /// @author Jean-Marc Henry /// @notice The data owner grants a user access to a particular datum, if the contract is paused this critical function is disabled /** @dev The owner grants access to request. The reason a new IPFS location is required, is because the data is encrypted with a symmetric key, shared by all users. However, it is encrypted uniquely with each user's public key. Storing the shared key encrypted for each user would be prohibitive on the blockchain. The solution then is to store them on IPFS, thus every time a user is added or removed, the IPFS address will be updated (i.e. because it is the hash of the data it contains). */ /// @param user The user(ethereum address) granted acces to the datum /// @param data_id The datum identifier to which the user is granted acces /// @param newContentLocation The IPFS digest, allowing to retrieve the encrypted data function grantAccess(address user, uint data_id, bytes32 newContentLocation) public onlyOwner() whenNotPaused() { access_list[data_id][user] = 2; // 2 means access granted data[data_id] = newContentLocation; // because the client has added the sharedKey for user, the content is updated emit LogAccessGranted(user, data_id, newContentLocation); } /// @author Jean-Marc Henry /// @notice The owner has decided to reject a user's request to share data /** @dev The owner refuses to grand access to the request. No need to update the IPFS address as no new key added or content modified. Note the use of the internal removeUserByData() function to keep everything in synch. */ /// @param user_id The user(ethereum address) being refused acces to the datum /// @param data_id The datum identifier to which the user is refused acces function refuseAccess(address user_id, uint data_id) public onlyOwner(){ removeUserByData(data_id,user_id); emit LogAccessRefused(user_id, data_id); } /// @author Jean-Marc Henry /// @notice The owner has decided to revoke a user's access to data /** @dev The owner revokes the access of user to some data. This, of course does not mean the user no longer has access to the data, as it is on IPFS, rather it means that any new content added to that shared data will not be accessible. The way it is done is by having the Dapp client generate a new shared key and encrypt it for the remaining users. Since, we do not store the encrypted shared keys on the blockchain, it is not a costly operation. */ /// @param user_id The user(ethereum address) whose access to the datum is being revoked /// @param data_id The datum identifier for which the user's access is revoked /// @param newContentLocation The IPFS digest, allowing to retrieve the encrypted data function revokeAccess(address user_id, uint data_id, bytes32 newContentLocation) public onlyOwner() { removeUserByData(data_id,user_id); data[data_id] = newContentLocation; // because the web client has removed the sharedKey for user, the content is updated emit LogAccessRevoked(user_id, data_id, newContentLocation); } /// @author Jean-Marc Henry /// @notice Retrieve the IPFS location /** @dev As described above, this will allow retriving the IPFS hash by means of base58 encoding and adding the constants describing the size and hash function used. */ /// @param data_id The datum identifier for which we are retrieving the IPFS location /// @return hash the bytes32 value of the digest of the ipfs hash function getDataLocation(uint data_id) public view returns (bytes32 hash) { return data[data_id]; } /// @author Jean-Marc Henry /// @notice update encrypted content and/or metadata, but not the keys /** @dev To be used when the owner changes something in the data, which will change the ipfs location */ /// @param data_id The datum identifier for which we are changing the IPFS location /// @param IPFSaddress The new IPFS digest, allowing to retrieve the encrypted data function updateContent(uint data_id, bytes32 IPFSaddress) public onlyOwner() { data[data_id] = IPFSaddress; emit LogDataUpdated(data_id, IPFSaddress); } /// @dev for a given data_id count the number of granted requests function countAuthorizedUsers(uint data_id) internal view returns (uint requestCount) { uint authorizedCount = 0; uint nb_users = users_by_data[data_id].length; for (uint i = 0; i < nb_users ; i++) { address current_user = users_by_data[data_id][i]; // tricky next line - since the user is not removed from the array // you need to verify that the index matches that of user_indexes_by_data[data_id][current_user if (user_indexes_by_data[data_id][current_user] == i) { if (access_list[data_id][current_user] == 2) { authorizedCount++; } } } return authorizedCount; } // for a given data_id, the function returns all the addresses that have access /// @author Jean-Marc Henry /// @notice For a given datum, retrive all authorized users /** @dev Useful to show who has access to what in the UI. */ /// @param data_id The datum identifier for which we are retrieving the authorized users /// @return r_the_users an array of addresses, representing the users having access the content function getAuthorizedUsersForDatum(uint data_id) public view returns ( address[] memory r_the_users) { uint array_index = 0; uint array_size = countAuthorizedUsers(data_id); uint nb_users = users_by_data[data_id].length; address[] memory the_users = new address[](array_size); for (uint i = 0; i < nb_users ; i++) { if (user_indexes_by_data[data_id][users_by_data[data_id][i]] == i) { if (access_list[data_id][users_by_data[data_id][i]] == 2) { the_users[array_index] = (users_by_data[data_id][i]); array_index++; } } } return the_users; } function countPendingRequests() internal view returns (uint) { uint count_requested = 0; for (uint datum = 0; datum < data_index; datum++) { uint nb_users = users_by_data[datum].length; for (uint i = 0; i < nb_users; i++) { if (user_indexes_by_data[datum][users_by_data[datum][i]] == i) { if (access_list[datum][users_by_data[datum][i]] == 1) { count_requested++; } } } } return count_requested; } /// @author Jean-Marc Henry /// @notice returns all the pending requests /** @dev To be used to tell the owner who requested access to what. To be noted, that the data is only meaningful if interpreted as an array of tuples. The (data_id,user) tuple tells you that the user has requested access to the data_id. */ /// @return r_data_ids in conjunction with r_users returns an array of tuples (data_id, user) /// @return r_users in conjunction with r_data_ids returns an array of tuples (data_id, user) function getAllPendingRequests() external view returns ( uint[] memory r_data_ids, address[] memory r_users) { uint array_index = 0; uint array_size = countPendingRequests(); uint[] memory data_ids = new uint[](array_size); address[] memory users = new address[](array_size); for (uint datum = 0; datum < data_index; datum++) { uint nb_users = users_by_data[datum].length; for (uint i = 0; i < nb_users; i++) { if (user_indexes_by_data[datum][users_by_data[datum][i]] == i) { if (access_list[datum][users_by_data[datum][i]] == 1) { data_ids[array_index] = (datum); users[array_index] = (users_by_data[datum][i]); array_index++; } } } } return (data_ids,users); } /// @author Jean-Marc Henry /// @notice for a given data_id and user, the function returns the access status /** @dev Returns the access status, which can be used to display appropriate info in the UI. The app may want to listen to events, to capture the rejection, approval of access and thus update the UI in a timely manner. */ /** @return status can be requested (1), or granted(2). The value 0 means no access, but it will not be returned as it is the equivalent of no value in a mapping, which is what the data structure uses*/ function getUserStatusForDatum(uint data_id, address user) public view returns (uint status) { status = access_list[data_id][user]; return status; } /// @author Jean-Marc Henry /// @notice For a given user, returns the public key /** @dev The public key can then be used to encrypt the shared symmetric key. */ /// @return pubx returns the X coordinate of the public key /// @return puby returns the Y coordinate of the public key function getPublicKey(address user) public view returns (bytes32 pubx, bytes32 puby) { return(user_keys[user].x,user_keys[user].y); } }
Jean-Marc Henry Request access for a user to a datum, providing his/her her public key This function needs to be called only the first time a requests access./ data_id The datum identifier to which the user is granted acces publicKeyX The Ethereum's public key's X coordinate publicKeyY The Ethereum's public key's Y coordinate emit debugInt(access_list[data_id][msg.sender]);
Subsequently, the client dapp can call the less gas hungry requestAccess() function. It stores the public key, counting on js client to provide the correct key. After all, no on is harmed except user if it is wrong, therefore there is no need to waste gas on verifying the key is valid. The exception is made here is to check that the key is not 0, as in a mapping this is the equivalent of no entry. function requestAccessWithKey(uint data_id, bytes32 publicKeyX, bytes32 publicKeyY) public { require((data_id < data_index), "data does not exist"); require(isPubKeyNotZero(publicKeyX,publicKeyY), "public key cannot be 0"); pubkey memory publicKey = pubkey(publicKeyX,publicKeyY); user_keys[msg.sender] = publicKey; addUserByData(data_id,msg.sender); emit LogAccessRequestWithPubKey(msg.sender, data_id, publicKeyX, publicKeyY); }
7,326,687
./full_match/42/0xfF3C21d478C4bd6E2d575bCc36EA2C38b75608FE/sources/UniswapV2Router02.sol
ADD LIQUIDITY create the pair if it doesn't exist yet uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired);
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { test1 = tokenA; test2 = tokenB; if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); test3 = "vao day"; test4 = amountADesired; test5 = reserveA; test6 = reserveB; uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); test7 = amountBOptimal; if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); test9 = "vao day "; } } }
9,575,918
/** *Submitted for verification at Etherscan.io on 2022-01-20 */ // Sources flattened with hardhat v2.8.2 https://hardhat.org // File contracts/solidity/proxy/IBeacon.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // File contracts/solidity/proxy/Proxy.sol pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // File contracts/solidity/util/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/solidity/proxy/Create2BeaconProxy.sol pragma solidity ^0.8.0; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * Slightly modified to allow using beacon proxies with Create2. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract Create2BeaconProxy is Proxy { /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor() payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _setBeacon(msg.sender, ""); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address beacon) { bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { beacon := sload(slot) } } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).childImplementation(); } /** * @dev Changes the proxy to use a new beacon. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).childImplementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed"); } } }
Returns the current implementation address of the associated beacon./
function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).childImplementation(); }
2,050,915
./full_match/5/0x42496Fcde8c8277da3cCbdA8ADdF66b0769bf0ea/sources/contracts/StakingDistributor.sol
adds a pool to the list note you should find an empty slot offchain before calling if there are no empty slots, pass in an occupied index to push we want to overwrite slots where possible if the passed in slot is not empty, push to the end
function addPool(uint256 index, address pool) external onlyGovernor { if (pools[index] == address(0)) { pools[index] = pool; pools.push(pool); } }
1,956,215
pragma solidity 0.5.15; pragma experimental ABIEncoderV2; import 'ROOT/IAugurCreationDataGetter.sol'; import 'ROOT/IAugurMarketDataGetter.sol'; import "ROOT/libraries/math/SafeMathUint256.sol"; import "ROOT/libraries/ContractExists.sol"; import "ROOT/libraries/token/IERC20.sol"; import "ROOT/external/IExchange.sol"; import "ROOT/trading/IFillOrder.sol"; import "ROOT/ICash.sol"; import "ROOT/trading/Order.sol"; import "ROOT/trading/IZeroXTrade.sol"; import "ROOT/trading/IAugurTrading.sol"; import 'ROOT/libraries/Initializable.sol'; import "ROOT/IAugur.sol"; import 'ROOT/libraries/token/IERC1155.sol'; import 'ROOT/libraries/LibBytes.sol'; import 'ROOT/uniswap/interfaces/IUniswapV2Factory.sol'; import 'ROOT/uniswap/interfaces/IUniswapV2Pair.sol'; import 'ROOT/uniswap/interfaces/IWETH.sol'; contract ParaZeroXTrade is Initializable, IZeroXTrade, IERC1155 { using SafeMathUint256 for uint256; using LibBytes for bytes; bool transferFromAllowed = false; // ERC20Token(address) bytes4 constant private ERC20_PROXY_ID = 0xf47261b0; // ERC1155Assets(address,uint256[],uint256[],bytes) bytes4 constant private MULTI_ASSET_PROXY_ID = 0x94cfcdd7; // ERC1155Assets(address,uint256[],uint256[],bytes) bytes4 constant private ERC1155_PROXY_ID = 0xa7cb5fb7; // EIP191 header for EIP712 prefix string constant internal EIP191_HEADER = "\x19\x01"; // EIP712 Domain Name value string constant internal EIP712_DOMAIN_NAME = "0x Protocol"; // EIP712 Domain Version value string constant internal EIP712_DOMAIN_VERSION = "2"; // EIP1271 Order With Hash Selector bytes4 constant public EIP1271_ORDER_WITH_HASH_SELECTOR = 0x3efe50c8; // Hash of the EIP712 Domain Separator Schema bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256( abi.encodePacked( "Order(", "address makerAddress,", "address takerAddress,", "address feeRecipientAddress,", "address senderAddress,", "uint256 makerAssetAmount,", "uint256 takerAssetAmount,", "uint256 makerFee,", "uint256 takerFee,", "uint256 expirationTimeSeconds,", "uint256 salt,", "bytes makerAssetData,", "bytes takerAssetData", "bytes makerFeeAssetData,", "bytes takerFeeAssetData", ")" )); // Hash of the EIP712 Domain Separator data // solhint-disable-next-line var-name-mixedcase bytes32 public EIP712_DOMAIN_HASH; IAugur public augur; IAugurTrading public augurTrading; IFillOrder public fillOrder; ICash public cash; IShareToken public shareToken; IExchange public exchange; IWETH public WETH; bool public token0IsCash; function initialize(IAugur _augur, IAugurTrading _augurTrading) external beforeInitialized { endInitialization(); augur = _augur; augurTrading = _augurTrading; cash = ICash(_augur.lookup("Cash")); require(cash != ICash(0)); shareToken = IShareToken(_augur.lookup("ShareToken")); require(shareToken != IShareToken(0)); exchange = IExchange(_augurTrading.lookup("ZeroXExchange")); require(exchange != IExchange(0)); fillOrder = IFillOrder(_augurTrading.lookup("FillOrder")); require(fillOrder != IFillOrder(0)); EIP712_DOMAIN_HASH = keccak256( abi.encodePacked( EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, keccak256(bytes(EIP712_DOMAIN_NAME)), keccak256(bytes(EIP712_DOMAIN_VERSION)), uint256(address(this)) ) ); } // ERC1155 Implementation /// @notice Transfers value amount of an _id from the _from address to the _to address specified. /// @dev MUST emit TransferSingle event on success. /// @param from Source address /// @param to Target address /// @param id ID of the token type /// @param value Transfer amount /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external { data; require(transferFromAllowed); emit TransferSingle(msg.sender, from, to, id, value); } /// @notice Send multiple types of Tokens from a 3rd party in one transfer (with safety call). /// @dev MUST emit TransferBatch event on success. /// @param from Source addresses /// @param to Target addresses /// @param ids IDs of each token type /// @param values Transfer amounts per token type /// @param data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data) external { data; require(transferFromAllowed); emit TransferBatch(msg.sender, from, to, ids, values); } /// @notice Get the balance of an account's Tokens. /// @param owner The address of the token holder /// @param id ID of the Token /// @return The _owner's balance of the Token type requested function balanceOf(address owner, uint256 id) external view returns (uint256) { (address _market, uint256 _price, uint8 _outcome, uint8 _type) = unpackTokenId(id); // NOTE: An invalid order type will cause a failure here. That is malformed input so we don't mind reverting in such a case Order.Types _orderType = Order.Types(_type); if (_orderType == Order.Types.Ask) { return askBalance(owner, IMarket(_market), _outcome, _price); } else if (_orderType == Order.Types.Bid) { return bidBalance(owner, IMarket(_market), _outcome, _price); } } function totalSupply(uint256 id) external view returns (uint256) { id; return 0; } function bidBalance(address _owner, IMarket _market, uint8 _outcome, uint256 _price) public view returns (uint256) { uint256 _numberOfOutcomes = _market.getNumberOfOutcomes(); // Figure out how many almost-complete-sets (just missing `outcome` share) the creator has uint256[] memory _shortOutcomes = new uint256[](_numberOfOutcomes - 1); uint256 _indexOutcome = 0; for (uint256 _i = 0; _i < _numberOfOutcomes - 1; _i++) { if (_i == _outcome) { _indexOutcome++; } _shortOutcomes[_i] = _indexOutcome; _indexOutcome++; } uint256 _attoSharesOwned = shareToken.lowestBalanceOfMarketOutcomes(_market, _shortOutcomes, _owner); uint256 _availableCash = cashAvailableForTransferFrom(_owner, address(fillOrder)); uint256 _attoSharesPurchasable = _availableCash.div(_price); return _attoSharesOwned.add(_attoSharesPurchasable); } function askBalance(address _owner, IMarket _market, uint8 _outcome, uint256 _price) public view returns (uint256) { uint256 _attoSharesOwned = shareToken.balanceOfMarketOutcome(_market, _outcome, _owner); uint256 _availableCash = cashAvailableForTransferFrom(_owner, address(fillOrder)); uint256 _attoSharesPurchasable = _availableCash.div(_market.getNumTicks().sub(_price)); return _attoSharesOwned.add(_attoSharesPurchasable); } function cashAvailableForTransferFrom(address _owner, address _sender) public view returns (uint256) { uint256 _balance = cash.balanceOf(_owner); uint256 _allowance = cash.allowance(_owner, _sender); return _balance.min(_allowance); } /// @notice Get the balance of multiple account/token pairs /// @param owners The addresses of the token holders /// @param ids ID of the Tokens /// @return The _owner's balance of the Token types requested function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory balances_) { balances_ = new uint256[](owners.length); for (uint256 _i = 0; _i < owners.length; _i++) { balances_[_i] = this.balanceOf(owners[_i], ids[_i]); } } function setApprovalForAll(address operator, bool approved) external { operator; approved; revert("Not supported"); } function isApprovedForAll(address owner, address operator) external view returns (bool) { owner; operator; return true; } // Trade functions /** * Perform Augur Trades using 0x signed orders * * @param _requestedFillAmount Share amount to fill * @param _fingerprint Fingerprint of the user to restrict affiliate fees * @param _tradeGroupId Random id to correlate these fills as one trade action * @param _unused IGNORED: The _maxProtocolFeeDai is only used on the non-Para ZeroXTrade * @param _maxTrades The maximum number of trades to actually take from the provided 0x orders * @param _orders Array of encoded Order struct data * @param _signatures Array of signature data * @return The amount the taker still wants */ function trade( uint256 _requestedFillAmount, bytes32 _fingerprint, bytes32 _tradeGroupId, uint256 _unused, uint256 _maxTrades, IExchange.Order[] memory _orders, bytes[] memory _signatures ) public payable returns (uint256) { _unused; require(_orders.length == _signatures.length); uint256 _fillAmountRemaining = _requestedFillAmount; transferFromAllowed = true; uint256 _protocolFee = exchange.protocolFeeMultiplier().mul(tx.gasprice); require(address(this).balance >= _protocolFee * _orders.length, "Insufficient ETH sent for protocol fee"); // Do the actual asset exchanges for (uint256 i = 0; i < _orders.length && _fillAmountRemaining != 0; i++) { IExchange.Order memory _order = _orders[i]; validateOrder(_order, _fillAmountRemaining); // Update 0x and pay protocol fee. This will also validate signatures and order state for us. IExchange.FillResults memory totalFillResults = fillOrderNoThrow( _order, _fillAmountRemaining, _signatures[i], _protocolFee ); if (totalFillResults.takerAssetFilledAmount == 0) { continue; } uint256 _amountTraded = doTrade(_order, totalFillResults.takerAssetFilledAmount, _fingerprint, _tradeGroupId, msg.sender); _fillAmountRemaining = _fillAmountRemaining.sub(_amountTraded); _maxTrades -= 1; if (_maxTrades == 0) { break; } } transferFromAllowed = false; if (address(this).balance > 0) { (bool _success,) = msg.sender.call.value(address(this).balance)(""); require(_success); } return _fillAmountRemaining; } function fillOrderNoThrow(IExchange.Order memory _order, uint256 _takerAssetFillAmount, bytes memory _signature, uint256 _protocolFee) internal returns (IExchange.FillResults memory fillResults) { bytes memory fillOrderCalldata = abi.encodeWithSelector( IExchange(address(0)).fillOrder.selector, _order, _takerAssetFillAmount, _signature ); (bool _didSucceed, bytes memory _returnData) = address(exchange).call.value(_protocolFee)(fillOrderCalldata); if (_didSucceed) { assert(_returnData.length == 160); fillResults = abi.decode(_returnData, (IExchange.FillResults)); } return fillResults; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn) { require(amountOut > 0); require(reserveIn > 0 && reserveOut > 0); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } function validateOrder(IExchange.Order memory _order, uint256 _fillAmountRemaining) internal view { require(_order.takerAssetData.equals(encodeTakerAssetData())); require(_order.takerAssetAmount == _order.makerAssetAmount); (IERC1155 _zeroXTradeTokenMaker, uint256 _tokenIdMaker) = getZeroXTradeTokenData(_order.makerAssetData); (address _market, , , ) = unpackTokenId(_tokenIdMaker); require(isOrderAmountValid(IMarket(_market), _fillAmountRemaining), "Order must be a multiple of the market trade increment"); require(_zeroXTradeTokenMaker == this); } function isOrderAmountValid(IMarket _market, uint256 _orderAmount) public view returns (bool) { uint256 _tradeInterval = IAugurMarketDataGetter(address(augur)).getMarketRecommendedTradeInterval(_market); return _orderAmount.isMultipleOf(_tradeInterval); } function cancelOrders(IExchange.Order[] memory _orders, bytes[] memory _signatures, uint256 _unused) public payable returns (bool) { _unused; require(_orders.length == _signatures.length); uint256 _protocolFee = exchange.protocolFeeMultiplier().mul(tx.gasprice); require(address(this).balance >= _protocolFee * _orders.length, "Insufficient ETH sent for protocol fee"); transferFromAllowed = true; for (uint256 i = 0; i < _orders.length; i++) { IExchange.Order memory _order = _orders[i]; bytes memory _signature = _signatures[i]; require(msg.sender == _order.makerAddress); IExchange.OrderInfo memory _orderInfo = exchange.getOrderInfo(_order); uint256 _amountRemaining = _order.takerAssetAmount.sub(_orderInfo.orderTakerAssetFilledAmount); exchange.fillOrder.value(_protocolFee)(_order, _amountRemaining, _signature); AugurOrderData memory _orderData = parseOrderData(_order); IUniverse _universe = IMarket(_orderData.marketAddress).getUniverse(); augurTrading.logZeroXOrderCanceled(address(_universe), _orderData.marketAddress, _order.makerAddress, _orderData.outcome, _orderData.price, _amountRemaining, uint8(_orderData.orderType), _orderInfo.orderHash); } transferFromAllowed = false; if (address(this).balance > 0) { (bool _success,) = msg.sender.call.value(address(this).balance)(""); require(_success); } return true; } function doTrade(IExchange.Order memory _order, uint256 _amount, bytes32 _fingerprint, bytes32 _tradeGroupId, address _taker) private returns (uint256 _amountFilled) { // parseOrderData will validate that the token being traded is the leigitmate one for the market AugurOrderData memory _augurOrderData = parseOrderData(_order); // If the signed order creator doesnt have enough funds we still want to continue and take their order out of the list // If the filler doesn't have funds this will just fail, which is fine if (!creatorHasFundsForTrade(_order, _amount)) { return 0; } // If the maker is also the taker we also just skip the trade but treat it as filled for amount remaining purposes if (_order.makerAddress == _taker) { return _amount; } (uint256 _amountRemaining, uint256 _fees) = fillOrder.fillZeroXOrder(IMarket(_augurOrderData.marketAddress), _augurOrderData.outcome, _augurOrderData.price, Order.Types(_augurOrderData.orderType), _order.makerAddress, _amount, _fingerprint, _tradeGroupId, _taker); _amountFilled = _amount.sub(_amountRemaining); logOrderFilled(_order, _augurOrderData, _taker, _tradeGroupId, _amountFilled, _fees); return _amountFilled; } function logOrderFilled(IExchange.Order memory _order, AugurOrderData memory _augurOrderData, address _taker, bytes32 _tradeGroupId, uint256 _amountFilled, uint256 _fees) private { bytes32 _orderHash = exchange.getOrderInfo(_order).orderHash; address[] memory _addressData = new address[](2); uint256[] memory _uint256Data = new uint256[](10); Order.Types _orderType = Order.Types(_augurOrderData.orderType); _addressData[0] = _order.makerAddress; _addressData[1] = _taker; _uint256Data[0] = _augurOrderData.price; _uint256Data[1] = 0; _uint256Data[2] = _augurOrderData.outcome; _uint256Data[5] = _fees; _uint256Data[6] = _amountFilled; _uint256Data[8] = 0; _uint256Data[9] = 0; augurTrading.logZeroXOrderFilled(IMarket(_augurOrderData.marketAddress).getUniverse(), IMarket(_augurOrderData.marketAddress), _orderHash, _tradeGroupId, uint8(_orderType), _addressData, _uint256Data); } function creatorHasFundsForTrade(IExchange.Order memory _order, uint256 _amount) public view returns (bool) { uint256 _tokenId = getTokenIdFromOrder(_order); return _amount <= this.balanceOf(_order.makerAddress, _tokenId); } function getTransferFromAllowed() external view returns (bool) { return transferFromAllowed; } /// @dev Encode MultiAsset proxy asset data into the format described in the AssetProxy contract specification. /// @param _market The address of the market to trade on /// @param _price The price used to trade /// @param _outcome The outcome to trade on /// @param _type Either BID == 0 or ASK == 1 /// @return AssetProxy-compliant asset data describing the set of assets. function encodeAssetData( IMarket _market, uint256 _price, uint8 _outcome, uint8 _type ) public view returns (bytes memory _assetData) { bytes[] memory _nestedAssetData = new bytes[](3); uint256[] memory _multiAssetValues = new uint256[](3); _nestedAssetData[0] = encodeTradeAssetData(_market, _price, _outcome, _type); _nestedAssetData[1] = encodeCashAssetData(); _nestedAssetData[2] = encodeShareAssetData(); _multiAssetValues[0] = 1; _multiAssetValues[1] = 0; _multiAssetValues[2] = 0; bytes memory _data = abi.encodeWithSelector( MULTI_ASSET_PROXY_ID, _multiAssetValues, _nestedAssetData ); return _data; } /// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. /// @param _market The address of the market to trade on /// @param _price The price used to trade /// @param _outcome The outcome to trade on /// @param _type Either BID == 0 or ASK == 1 /// @return AssetProxy-compliant asset data describing the set of assets. function encodeTradeAssetData( IMarket _market, uint256 _price, uint8 _outcome, uint8 _type ) private view returns (bytes memory _assetData) { uint256[] memory _tokenIds = new uint256[](1); uint256[] memory _tokenValues = new uint256[](1); uint256 _tokenId = getTokenId(address(_market), _price, _outcome, _type); _tokenIds[0] = _tokenId; _tokenValues[0] = 1; bytes memory _callbackData = new bytes(0); _assetData = abi.encodeWithSelector( ERC1155_PROXY_ID, address(this), _tokenIds, _tokenValues, _callbackData ); return _assetData; } /// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeCashAssetData() private view returns (bytes memory _assetData) { _assetData = abi.encodeWithSelector( ERC20_PROXY_ID, address(cash) ); return _assetData; } /// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeShareAssetData() private view returns (bytes memory _assetData) { uint256[] memory _tokenIds = new uint256[](0); uint256[] memory _tokenValues = new uint256[](0); bytes memory _callbackData = new bytes(0); _assetData = abi.encodeWithSelector( ERC1155_PROXY_ID, address(shareToken), _tokenIds, _tokenValues, _callbackData ); return _assetData; } /// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. /// @return AssetProxy-compliant asset data describing the set of assets. function encodeTakerAssetData() private view returns (bytes memory _assetData) { uint256[] memory _tokenIds = new uint256[](0); uint256[] memory _tokenValues = new uint256[](0); bytes memory _callbackData = new bytes(0); _assetData = abi.encodeWithSelector( ERC1155_PROXY_ID, address(this), _tokenIds, _tokenValues, _callbackData ); return _assetData; } function getTokenId(address _market, uint256 _price, uint8 _outcome, uint8 _type) public pure returns (uint256 _tokenId) { // NOTE: we're assuming no one needs a full uint256 for the price value here and cutting to uint80 so we can pack this in a uint256. bytes memory _tokenIdBytes = abi.encodePacked(_market, uint80(_price), _outcome, _type); assembly { _tokenId := mload(add(_tokenIdBytes, add(0x20, 0))) } } function unpackTokenId(uint256 _tokenId) public pure returns (address _market, uint256 _price, uint8 _outcome, uint8 _type) { assembly { _market := shr(96, and(_tokenId, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)) _price := shr(16, and(_tokenId, 0x0000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFF0000)) _outcome := shr(8, and(_tokenId, 0x000000000000000000000000000000000000000000000000000000000000FF00)) _type := and(_tokenId, 0x00000000000000000000000000000000000000000000000000000000000000FF) } } /// @dev Decode MultiAsset asset data from the format described in the AssetProxy contract specification. /// @param _assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets. /// @return The ERC-1155 AssetProxy identifier, the address of this ERC-1155 /// contract hosting the assets, an array of the identifiers of the /// assets to be traded, an array of asset amounts to be traded, and /// callback data. Each element of the arrays corresponds to the /// same-indexed element of the other array. Return values specified as /// `memory` are returned as pointers to locations within the memory of /// the input parameter `assetData`. function decodeAssetData(bytes memory _assetData) public view returns ( bytes4 _assetProxyId, address _tokenAddress, uint256[] memory _tokenIds, uint256[] memory _tokenValues, bytes memory _callbackData ) { // Read the bytes4 from array memory assembly { _assetProxyId := mload(add(_assetData, 32)) // Solidity does not require us to clean the trailing bytes. We do it anyway _assetProxyId := and(_assetProxyId, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } require(_assetProxyId == MULTI_ASSET_PROXY_ID, "WRONG_PROXY_ID"); uint256[] memory _amounts; bytes[] memory _nestedAssetData; // Slice the selector off the asset data bytes memory _noSelectorAssetData = _assetData.slice(4, _assetData.length); (_amounts, _nestedAssetData) = abi.decode(_noSelectorAssetData, (uint256[], bytes[])); // Validate storage refs against the decoded values. { require(_amounts.length == 3); require(_amounts[0] == 1); require(_amounts[1] == 0); require(_amounts[2] == 0); require(_nestedAssetData[1].equals(encodeCashAssetData())); require(_nestedAssetData[2].equals(encodeShareAssetData())); } return decodeTradeAssetData(_nestedAssetData[0]); } /// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. /// @param _assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets. /// @return The ERC-1155 AssetProxy identifier, the address of this ERC-1155 /// contract hosting the assets, an array of the identifiers of the /// assets to be traded, an array of asset amounts to be traded, and /// callback data. Each element of the arrays corresponds to the /// same-indexed element of the other array. Return values specified as /// `memory` are returned as pointers to locations within the memory of /// the input parameter `assetData`. function decodeTradeAssetData(bytes memory _assetData) public pure returns ( bytes4 _assetProxyId, address _tokenAddress, uint256[] memory _tokenIds, uint256[] memory _tokenValues, bytes memory _callbackData ) { // Read the bytes4 from array memory assembly { _assetProxyId := mload(add(_assetData, 32)) // Solidity does not require us to clean the trailing bytes. We do it anyway _assetProxyId := and(_assetProxyId, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } require(_assetProxyId == ERC1155_PROXY_ID, "WRONG_PROXY_ID"); assembly { let _length := mload(_assetData) // Skip the length (of bytes variable) and the selector to get to the first parameter. _assetData := add(_assetData, 36) // Read the value of the first parameter: _tokenAddress := mload(_assetData) _tokenIds := add(_assetData, mload(add(_assetData, 32))) _tokenValues := add(_assetData, mload(add(_assetData, 64))) _callbackData := add(_assetData, mload(add(_assetData, 96))) } return ( _assetProxyId, _tokenAddress, _tokenIds, _tokenValues, _callbackData ); } function parseOrderData(IExchange.Order memory _order) public view returns (AugurOrderData memory _data) { (/* bytes4 _assetProxyId */, /* address _tokenAddress */ , uint256[] memory _tokenIds, /* uint256[] memory _tokenValues */, /* bytes memory _callbackData */) = decodeAssetData(_order.makerAssetData); (address _market, uint256 _price, uint8 _outcome, uint8 _type) = unpackTokenId(_tokenIds[0]); _data.marketAddress = _market; _data.price = _price; _data.orderType = _type; _data.outcome = _outcome; } function getZeroXTradeTokenData(bytes memory _assetData) public view returns (IERC1155 _token, uint256 _tokenId) { (/* bytes4 _assetProxyId */, address _tokenAddress, uint256[] memory _tokenIds, /* uint256[] memory _tokenValues */, /* bytes memory _callbackData */) = decodeAssetData(_assetData); _tokenId = _tokenIds[0]; _token = IERC1155(_tokenAddress); } function getTokenIdFromOrder(IExchange.Order memory _order) public view returns (uint256 _tokenId) { (/* bytes4 _assetProxyId */, /* address _tokenAddress */, uint256[] memory _tokenIds, /* uint256[] memory _tokenValues */, /* bytes memory _callbackData */) = decodeAssetData(_order.makerAssetData); _tokenId = _tokenIds[0]; } function createZeroXOrder(uint8 _type, uint256 _attoshares, uint256 _price, address _market, uint8 _outcome, uint256 _expirationTimeSeconds, uint256 _salt) public view returns (IExchange.Order memory _zeroXOrder, bytes32 _orderHash) { return createZeroXOrderFor(msg.sender, _type, _attoshares, _price, _market, _outcome, _expirationTimeSeconds, _salt); } function createZeroXOrderFor(address _maker, uint8 _type, uint256 _attoshares, uint256 _price, address _market, uint8 _outcome, uint256 _expirationTimeSeconds, uint256 _salt) public view returns (IExchange.Order memory _zeroXOrder, bytes32 _orderHash) { bytes memory _assetData = encodeAssetData(IMarket(_market), _price, _outcome, _type); require(isOrderAmountValid(IMarket(_market), _attoshares), "Order must be a multiple of the market trade increment"); _zeroXOrder.makerAddress = _maker; _zeroXOrder.makerAssetAmount = _attoshares; _zeroXOrder.takerAssetAmount = _attoshares; _zeroXOrder.expirationTimeSeconds = _expirationTimeSeconds; _zeroXOrder.salt = _salt; _zeroXOrder.makerAssetData = _assetData; _zeroXOrder.takerAssetData = encodeTakerAssetData(); _orderHash = exchange.getOrderInfo(_zeroXOrder).orderHash; } function encodeEIP1271OrderWithHash( IExchange.Order calldata _zeroXOrder, bytes32 _orderHash ) external pure returns (bytes memory encoded) { return abi.encodeWithSelector( EIP1271_ORDER_WITH_HASH_SELECTOR, _zeroXOrder, _orderHash ); } function () external payable {} }
Get the balance of an account's Tokens. owner The address of the token holder id ID of the Token return The _owner's balance of the Token type requested NOTE: An invalid order type will cause a failure here. That is malformed input so we don't mind reverting in such a case
function balanceOf(address owner, uint256 id) external view returns (uint256) { (address _market, uint256 _price, uint8 _outcome, uint8 _type) = unpackTokenId(id); Order.Types _orderType = Order.Types(_type); if (_orderType == Order.Types.Ask) { return askBalance(owner, IMarket(_market), _outcome, _price); return bidBalance(owner, IMarket(_market), _outcome, _price); } }
2,547,873