file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/42/0x3e1cE2fF8382dc5D80E71304Ea40c9d49adD0372/sources/FlexibleLeverageStrategyAdapter.sol
Dependency file: contracts/interfaces/IBaseManager.sol/ pragma solidity 0.6.10; import { ISetToken } from "contracts/interfaces/ISetToken.sol";
interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; }
3,470,279
./full_match/1/0xee16C7C2A2A6E650E16916B0651792Ca0DdACf70/sources/contracts/sale/EarlySale.sol
View the total amount of ETH spent by a user _user, address of the user/
function getETHSpent(address _user) external view returns (uint256) { return _investorToEthSpent[_user]; }
9,771,059
pragma solidity ^0.5.0; import "zos-lib/contracts/Initializable.sol"; import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; import "../ownership/OracleManageable.sol"; /** * @title AccountManager */ contract AccountMapper is Initializable, OracleManageable { using ECDSA for bytes32; event AccountAdded(address indexed foreignAccountAddress, address indexed localAccountAddress); event AccountRemoved(address indexed foreignAccountAddress, address indexed localAccountAddress); mapping(address => address) private accountForeignToLocal; mapping(address => address) private accountLocalToForeign; function initialize(address owner, address oracle, address foreignOracle) public initializer { OracleManageable.initialize(owner, oracle, foreignOracle); } /** * @dev Add account mapping. * @notice Reverts if not called by localAccount owner * or if account is already mapped * or localAccountAddress is a contract * or signature is not valid. * @param foreignAccountAddress The address of ethereum chain account. * @param localAccountAddress The address of local chain account. * @param signature The signature signed with foreignAddress`s private key */ function addAccount( address foreignAccountAddress, address localAccountAddress, bytes memory signature ) public { require(msg.sender == localAccountAddress, "not called by local account owner"); require(!isLocalAccountAdded(localAccountAddress), "local account already added"); require(!isForeignAccountAdded(foreignAccountAddress), "foreign account already added"); require(_isValidAccountSignature(foreignAccountAddress, localAccountAddress, signature), "invalid signature"); accountForeignToLocal[foreignAccountAddress] = localAccountAddress; accountLocalToForeign[localAccountAddress] = foreignAccountAddress; emit AccountAdded(foreignAccountAddress, localAccountAddress); } /** * @dev Remove account mapping * @notice Reverts if not called by localAccountAddress owner * or if account is not mapped or signature is not valid. * @param foreignAccountAddress The address of ethereum chain account. * @param localAccountAddress The address of local chain account. * @param signature The signature signed with foreignAddress`s private key */ function removeAccount( address foreignAccountAddress, address localAccountAddress, bytes memory signature ) public { require(msg.sender == localAccountAddress, "not called by local account owner"); require(isAccountMapped(foreignAccountAddress, localAccountAddress), "account is not added"); require(_isValidAccountSignature(foreignAccountAddress, localAccountAddress, signature), "invalid signature"); accountForeignToLocal[foreignAccountAddress] = address(0); accountLocalToForeign[localAccountAddress] = address(0); emit AccountRemoved(foreignAccountAddress, localAccountAddress); } /** * @param foreignAccountAddress The address of ethereum chain account. * @param localAccountAddress The address of local chain account. * @return true if account is already mapped. */ function isAccountMapped( address foreignAccountAddress, address localAccountAddress ) public view returns (bool) { return accountForeignToLocal[foreignAccountAddress] == localAccountAddress && accountLocalToForeign[localAccountAddress] == foreignAccountAddress; } /** * @param localAccountAddress The address of local chain account. * @return true if account is already mapped. */ function isLocalAccountAdded(address localAccountAddress) public view returns (bool) { return accountLocalToForeign[localAccountAddress] != address(0); } /** * @param foreignAccountAddress The address of ethereum chain account. * @return true if account is already mapped. */ function isForeignAccountAdded(address foreignAccountAddress) public view returns (bool) { return accountForeignToLocal[foreignAccountAddress] != address(0); } /** * @return The local chain account address of given ethereum chain account address. */ function getLocalAccountOf(address foreignAccountAddress) public view returns (address) { return accountForeignToLocal[foreignAccountAddress]; } /** * @return The ethereum chain account address of given local chain account address. */ function getForeignAccountOf(address localAccountAddress) public view returns (address) { return accountLocalToForeign[localAccountAddress]; } /** * @dev Check given signature is valid account signature. * @return true if signature is valid */ function _isValidAccountSignature( address foreignAccountAddress, address localAccountAddress, bytes memory signature ) private pure returns (bool) { return keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(foreignAccountAddress, localAccountAddress)) )).recover(signature) == foreignAccountAddress; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
Add account mapping. Reverts if not called by localAccount owner or if account is already mapped or localAccountAddress is a contract or signature is not valid. foreignAccountAddress The address of ethereum chain account. localAccountAddress The address of local chain account. signature The signature signed with foreignAddress`s private key/
function addAccount( address foreignAccountAddress, address localAccountAddress, bytes memory signature ) public { require(msg.sender == localAccountAddress, "not called by local account owner"); require(!isLocalAccountAdded(localAccountAddress), "local account already added"); require(!isForeignAccountAdded(foreignAccountAddress), "foreign account already added"); require(_isValidAccountSignature(foreignAccountAddress, localAccountAddress, signature), "invalid signature"); accountForeignToLocal[foreignAccountAddress] = localAccountAddress; accountLocalToForeign[localAccountAddress] = foreignAccountAddress; emit AccountAdded(foreignAccountAddress, localAccountAddress); }
2,499,361
// SPDX-License-Identifier: MIT pragma solidity ^0.7.5; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title ERC998ERC20 Top-Down Composable Non-Fungible Token /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md /// Note: the ERC-165 identifier for this interface is 0x7294ffed interface IERC998ERC20TopDown is IERC721 { /// @dev This emits when a token receives ERC20 tokens. /// @param _from The prior owner of the token. /// @param _toTokenId The token that receives the ERC20 tokens. /// @param _erc20Contract The ERC20 contract. /// @param _value The number of ERC20 tokens received. event ReceivedERC20( address indexed _from, uint256 indexed _toTokenId, address indexed _erc20Contract, uint256 _value ); /// @dev This emits when a token transfers ERC20 tokens. /// @param _fromTokenId The token that owned the ERC20 tokens. /// @param _to The address that receives the ERC20 tokens. /// @param _erc20Contract The ERC20 contract. /// @param _value The number of ERC20 tokens transferred. event TransferERC20( uint256 indexed _fromTokenId, address indexed _to, address indexed _erc20Contract, uint256 _value ); /// @notice A token receives ERC20 tokens /// @param _from The prior owner of the ERC20 tokens /// @param _value The number of ERC20 tokens received /// @param _data Up to the first 32 bytes contains an integer which is the receiving tokenId. function tokenFallback( address _from, uint256 _value, bytes calldata _data ) external; /// @notice Look up the balance of ERC20 tokens for a specific token and ERC20 contract /// @param _tokenId The token that owns the ERC20 tokens /// @param _erc20Contract The ERC20 contract /// @return The number of ERC20 tokens owned by a token from an ERC20 contract function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256); /// @notice Transfer ERC20 tokens to address /// @param _tokenId The token to transfer from /// @param _to The address to send the ERC20 tokens to /// @param _erc20Contract The ERC20 contract /// @param _value The number of ERC20 tokens to transfer function transferERC20( uint256 _tokenId, address _to, address _erc20Contract, uint256 _value ) external; /// @notice Transfer ERC20 tokens to address or ERC20 top-down composable /// @param _tokenId The token to transfer from /// @param _to The address to send the ERC20 tokens to /// @param _erc223Contract The ERC223 token contract /// @param _value The number of ERC20 tokens to transfer /// @param _data Additional data with no specified format, can be used to specify tokenId to transfer to function transferERC223( uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes calldata _data ) external; /// @notice Get ERC20 tokens from ERC20 contract. /// @param _from The current owner address of the ERC20 tokens that are being transferred. /// @param _tokenId The token to transfer the ERC20 tokens to. /// @param _erc20Contract The ERC20 token contract /// @param _value The number of ERC20 tokens to transfer function getERC20( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) external; } /// @dev The ERC-165 identifier for this interface is 0xc5fd96cd interface ERC998ERC20TopDownEnumerable { /// @notice Get the number of ERC20 contracts that token owns ERC20 tokens from /// @param _tokenId The token that owns ERC20 tokens. /// @return uint256 The number of ERC20 contracts function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); /// @notice Get an ERC20 contract that token owns ERC20 tokens from by index /// @param _tokenId The token that owns ERC20 tokens. /// @param _index The index position of the ERC20 contract. /// @return address The ERC20 contract function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); }
The ERC-165 identifier for this interface is 0xc5fd96cd
interface ERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); } }
12,864,517
/** *Submitted for verification at Etherscan.io on 2022-04-14 */ // File: contracts/interfaces/ILayerZeroUserApplicationConfig.sol pragma solidity >=0.5.0; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig( uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config ) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; } // File: contracts/interfaces/ILayerZeroEndpoint.sol pragma solidity >=0.5.0; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send( uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload( uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint256 _gasLimit, bytes calldata _payload ) external; // @notice get the inboundNonce of a receiver from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees( uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam ) external view returns (uint256 nativeFee, uint256 zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload( uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload ) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint256 _configType ) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); } // File: contracts/interfaces/ILayerZeroReceiver.sol pragma solidity >=0.5.0; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _payload - the signed payload is the UA bytes has encoded to be sent function lzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) external; } // 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/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/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/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/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Address.sol // 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/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/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/NonblockingReceiver.sol pragma solidity ^0.8.6; abstract contract NonblockingReceiver is Ownable, ILayerZeroReceiver { ILayerZeroEndpoint internal endpoint; struct FailedMessages { uint256 payloadLength; bytes32 payloadHash; } mapping(uint16 => mapping(bytes => mapping(uint256 => FailedMessages))) public failedMessages; mapping(uint16 => bytes) public trustedRemoteLookup; event MessageFailed( uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload ); function lzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) external override { require(msg.sender == address(endpoint)); // boilerplate! lzReceive must be called by the endpoint for security require( _srcAddress.length == trustedRemoteLookup[_srcChainId].length && keccak256(_srcAddress) == keccak256(trustedRemoteLookup[_srcChainId]), "NonblockingReceiver: invalid source sending contract" ); // try-catch all errors/exceptions // having failed messages does not block messages passing try this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload) { // do nothing } catch { // error / exception failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages( _payload.length, keccak256(_payload) ); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload); } } function onLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) public { // only internal transaction require( msg.sender == address(this), "NonblockingReceiver: caller must be Bridge." ); // handle incoming message _LzReceive(_srcChainId, _srcAddress, _nonce, _payload); } // abstract function function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _txParam ) internal { endpoint.send{value: msg.value}( _dstChainId, trustedRemoteLookup[_dstChainId], _payload, _refundAddress, _zroPaymentAddress, _txParam ); } function retryMessage( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes calldata _payload ) external payable { // assert there is message to retry FailedMessages storage failedMsg = failedMessages[_srcChainId][ _srcAddress ][_nonce]; require( failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message" ); require( _payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload" ); // clear the stored message failedMsg.payloadLength = 0; failedMsg.payloadHash = bytes32(0); // execute the message. revert if it fails again this.onLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } function setTrustedRemote(uint16 _chainId, bytes calldata _trustedRemote) external onlyOwner { trustedRemoteLookup[_chainId] = _trustedRemote; } } // File: contracts/OmniSneaker_ETH.sol pragma solidity ^0.8.7; // ____ __ ____ ___________ _ ___________ __ __ __________ _____ // / __ \/ |/ / | / / _/ ___// | / / ____/ | / //_// ____/ __ \/ ___/ // / / / / /|_/ / |/ // / \__ \/ |/ / __/ / /| | / ,< / __/ / /_/ /\__ \ /// /_/ / / / / /| // / ___/ / /| / /___/ ___ |/ /| |/ /___/ _, _/___/ / //\____/_/ /_/_/ |_/___//____/_/ |_/_____/_/ |_/_/ |_/_____/_/ |_|/____/ // contract OmniSneaker is Ownable, ERC721, NonblockingReceiver { address public _owner; string private baseURI; uint256 nextTokenId = 0; uint256 MAX_MINT = 430; uint256 gasForDestinationLzReceive = 350000; constructor(string memory baseURI_, address _layerZeroEndpoint) ERC721("OmniSneaker", "OS") { _owner = msg.sender; endpoint = ILayerZeroEndpoint(_layerZeroEndpoint); baseURI = baseURI_; } /** * pre-mint for community giveaways */ function devMint(uint8 numTokens) public onlyOwner { require(nextTokenId + numTokens <= MAX_MINT, "Mint exceeds supply"); for (uint256 i = 0; i < numTokens; i++) { _safeMint(msg.sender, ++nextTokenId); } } // mint function // you can choose to mint 1 or 2 // mint is free, but payments are accepted function mint(uint8 numTokens) external payable { require(numTokens < 3, "GG: Max 2 NFTs per transaction"); require( nextTokenId + numTokens <= MAX_MINT, "GG: Mint exceeds supply" ); _safeMint(msg.sender, ++nextTokenId); if (numTokens == 2) { _safeMint(msg.sender, ++nextTokenId); } } // This function transfers the nft from your address on the // source chain to the same address on the destination chain function traverseChains(uint16 _chainId, uint256 tokenId) public payable { require( msg.sender == ownerOf(tokenId), "You must own the token to traverse" ); require( trustedRemoteLookup[_chainId].length > 0, "This chain is currently unavailable for travel" ); // burn NFT, eliminating it from circulation on src chain _burn(tokenId); // abi.encode() the payload with the values to send bytes memory payload = abi.encode(msg.sender, tokenId); // encode adapterParams to specify more gas for the destination uint16 version = 1; bytes memory adapterParams = abi.encodePacked( version, gasForDestinationLzReceive ); // get the fees we need to pay to LayerZero + Relayer to cover message delivery // you will be refunded for extra gas paid (uint256 messageFee, ) = endpoint.estimateFees( _chainId, address(this), payload, false, adapterParams ); require( msg.value >= messageFee, "GG: msg.value not enough to cover messageFee. Send gas for message fees" ); endpoint.send{value: msg.value}( _chainId, // destination chainId trustedRemoteLookup[_chainId], // destination address of nft contract payload, // abi.encoded()'ed bytes payable(msg.sender), // refund address address(0x0), // 'zroPaymentAddress' unused for this adapterParams // txParameters ); } function setBaseURI(string memory URI) external onlyOwner { baseURI = URI; } function donate() external payable { // thank you } // This allows the devs to receive kind donations function withdraw(uint256 amt) external onlyOwner { (bool sent, ) = payable(_owner).call{value: amt}(""); require(sent, "GG: Failed to withdraw Ether"); } // just in case this fixed variable limits us from future integrations function setGasForDestinationLzReceive(uint256 newVal) external onlyOwner { gasForDestinationLzReceive = newVal; } // ------------------ // Internal Functions // ------------------ function _LzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal override { // decode (address toAddr, uint256 tokenId) = abi.decode( _payload, (address, uint256) ); // mint the tokens back into existence on destination chain _safeMint(toAddr, tokenId); } function _baseURI() internal view override returns (string memory) { return baseURI; } }
only internal transaction handle incoming message
function onLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) public { require( msg.sender == address(this), "NonblockingReceiver: caller must be Bridge." ); _LzReceive(_srcChainId, _srcAddress, _nonce, _payload); }
7,857,230
/** *Submitted for verification at BscScan.com on 2021-04-06 */ // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IPeanutFactory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function FEE_RATE_DENOMINATOR() external view returns (uint256); function feeRateNumerator() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeToRate() external view returns (uint256); function initCodeHash() external view returns (bytes32); function pairFeeToRate(address) external view returns (uint256); function pairFees(address) external view returns (uint256); 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; function addPair(address) external returns (bool); function delPair(address) external returns (bool); function getSupportListLength() external view returns (uint256); function isSupportPair(address pair) external view returns (bool); function getSupportPair(uint256 index) external view returns (address); function setFeeRateNumerator(uint256) external; function setPairFees(address pair, uint256 fee) external; function setDefaultFeeToRate(uint256) external; function setPairFeeToRate(address pair, uint256 rate) external; function getPairFees(address) external view returns (uint256); function getPairRate(address) external view returns (uint256); function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1); function pairFor(address tokenA, address tokenB) external view returns (address pair); function getReserves(address tokenA, address tokenB) external view returns (uint256 reserveA, uint256 reserveB); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut, address token0, address token1 ) external view returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut, address token0, address token1 ) external view 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); } interface IPeanutPair { 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 Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); 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; } interface IPeanutERC20 { 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; } interface IERC20 { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } interface IswapV2Callee { function swapV2Call( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; } library SafeMath { uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wad() public pure returns (uint256) { return WAD; } function ray() public pure returns (uint256) { return RAY; } 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) { // 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; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / WAD; } function wmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), WAD / 2) / WAD; } function rmul(uint256 a, uint256 b) internal pure returns (uint256) { return mul(a, b) / RAY; } function rmulRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, b), RAY / 2) / RAY; } function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, WAD), b); } function wdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, WAD), b / 2) / b; } function rdiv(uint256 a, uint256 b) internal pure returns (uint256) { return div(mul(a, RAY), b); } function rdivRound(uint256 a, uint256 b) internal pure returns (uint256) { return add(mul(a, RAY), b / 2) / b; } function wpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = WAD; while (n > 0) { if (n % 2 != 0) { result = wmul(result, x); } x = wmul(x, x); n /= 2; } return result; } function rpow(uint256 x, uint256 n) internal pure returns (uint256) { uint256 result = RAY; while (n > 0) { if (n % 2 != 0) { result = rmul(result, x); } x = rmul(x, x); n /= 2; } return result; } } library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } 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). *5 * 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)); } } contract PeanutERC20 is IPeanutERC20 { using SafeMath for uint256; string public constant name = "PEANUT LP Token"; string public constant symbol = "PEANUT LP"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public { uint256 chainId; assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this) ) ); } function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub( value ); } _transfer(from, to, value); return true; } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "PeanutSwap: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "PeanutSwap: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } contract PeanutPair is IPeanutPair, PeanutERC20 { using SafeMath for uint256; using UQ112x112 for uint224; uint256 public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint256 private unlocked = 1; modifier lock() { require(unlocked == 1, "PeanutSwap: LOCKED"); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer( address token, address to, uint256 value ) private { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(SELECTOR, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "PeanutSwap: TRANSFER_FAILED" ); } event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, "PeanutSwap: FORBIDDEN"); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update( uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1 ) private { require( balance0 <= uint112(-1) && balance1 <= uint112(-1), "PeanutSwap: OVERFLOW" ); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IPeanutFactory(factory).feeTo(); feeOn = feeTo != address(0) && IPeanutFactory(factory).getPairRate(address(this)) != 9; uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = SafeMath.sqrt( uint256(_reserve0).mul(_reserve1) ); uint256 rootKLast = SafeMath.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK .mul(IPeanutFactory(factory).getPairRate(address(this))) .add(rootKLast); //分母 // 流动性=分子/分母; uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint256 liquidity) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = SafeMath.sqrt(amount0.mul(amount1)).sub( MINIMUM_LIQUIDITY ); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = SafeMath.min( amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1 ); } require(liquidity > 0, "PeanutSwap: INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint256 amount0, uint256 amount1) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint256 balance0 = IERC20(_token0).balanceOf(address(this)); uint256 balance1 = IERC20(_token1).balanceOf(address(this)); uint256 liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require( amount0 > 0 && amount1 > 0, "PeanutSwap: INSUFFICIENT_LIQUIDITY_BURNED" ); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external lock { require( amount0Out > 0 || amount1Out > 0, "PeanutSwap: INSUFFICIENT_OUTPUT_AMOUNT" ); (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings require( amount0Out < _reserve0 && amount1Out < _reserve1, "PeanutSwap: INSUFFICIENT_LIQUIDITY" ); uint256 balance0; uint256 balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, "PeanutSwap: INVALID_TO"); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IswapV2Callee(to).swapV2Call( msg.sender, amount0Out, amount1Out, data ); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require( amount0In > 0 || amount1In > 0, "PeanutSwap: INSUFFICIENT_INPUT_AMOUNT" ); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint256 balance0Adjusted = balance0.mul(1e4).sub( amount0In.mul( IPeanutFactory(factory).getPairFees(address(this)) ) ); uint256 balance1Adjusted = balance1.mul(1e4).sub( amount1In.mul( IPeanutFactory(factory).getPairFees(address(this)) ) ); require( balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1e8), "PeanutSwap: K" ); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer( _token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0) ); _safeTransfer( _token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1) ); } // force reserves to match balances function sync() external lock { _update( IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1 ); } } contract PeanutFactory is IPeanutFactory { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _supportList; uint256 public constant FEE_RATE_DENOMINATOR = 1e4; uint256 public feeRateNumerator = 300; //分子 ,150-basis-point fees earned by,基点费,1个基点等于1%的百分之一 0.3% address public feeTo; address public feeToSetter; uint256 public feeToRate = 30; //3个基点,万分之3 bytes32 public initCodeHash; mapping(address => uint256) public pairFeeToRate; mapping(address => uint256) public pairFees; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; initCodeHash = keccak256( abi.encodePacked(type(PeanutPair).creationCode) ); } function allPairsLength() external view returns (uint256) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, "PeanutSwapFactory: IDENTICAL_ADDRESSES"); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "PeanutSwapFactory: ZERO_ADDRESS"); require( getPair[token0][token1] == address(0), "PeanutSwapFactory: PAIR_EXISTS" ); // single check is sufficient bytes memory bytecode = type(PeanutPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IPeanutPair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( _feeToSetter != address(0), "PeanutSwapFactory: FeeToSetter is zero address" ); feeToSetter = _feeToSetter; } function addPair(address pair) external returns (bool) { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( pair != address(0), "PeanutSwapFactory: pair is the zero address" ); return EnumerableSet.add(_supportList, pair); } function delPair(address pair) external returns (bool) { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( pair != address(0), "PeanutSwapFactory: pair is the zero address" ); return EnumerableSet.remove(_supportList, pair); } function getSupportListLength() public view returns (uint256) { return EnumerableSet.length(_supportList); } function isSupportPair(address pair) public view returns (bool) { return EnumerableSet.contains(_supportList, pair); } function getSupportPair(uint256 index) external view returns (address) { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require(index <= getSupportListLength() - 1, "index out of bounds"); return EnumerableSet.at(_supportList, index); } // Set default fee ,max is 5% function setFeeRateNumerator(uint256 _feeRateNumerator) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( _feeRateNumerator <= 500, "PeanutSwapFactory: EXCEEDS_FEE_RATE_DENOMINATOR" ); feeRateNumerator = _feeRateNumerator; } // Set pair fee , max is 5% function setPairFees(address pair, uint256 fee) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require(fee <= 500, "PeanutSwapFactory: EXCEEDS_FEE_RATE_DENOMINATOR"); pairFees[pair] = fee; } // Set the default fee rate ,if set to 1/10 no handling fee function setDefaultFeeToRate(uint256 rate) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( rate > 0 && rate <= 10, "PeanutSwapFactory: FEE_TO_RATE_OVERFLOW" ); feeToRate = rate.sub(1); } // Set the commission rate of the pair ,if set to 1/10 no handling fee function setPairFeeToRate(address pair, uint256 rate) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( rate > 0 && rate <= 10, "PeanutSwapFactory: FEE_TO_RATE_OVERFLOW" ); pairFeeToRate[pair] = rate.sub(1); } function getPairFees(address pair) public view returns (uint256) { require( pair != address(0), "PeanutSwapFactory: pair is the zero address" ); if (isSupportPair(pair)) { return pairFees[pair]; } else { return feeRateNumerator; } } function getPairRate(address pair) external view returns (uint256) { require( pair != address(0), "PeanutSwapFactory: pair is the zero address" ); if (isSupportPair(pair)) { return pairFeeToRate[pair]; } else { return feeToRate; } } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) public pure returns (address token0, address token1) { require(tokenA != tokenB, "PeanutSwapFactory: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "PeanutSwapFactory: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address tokenA, address tokenB) public view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", address(this), keccak256(abi.encodePacked(token0, token1)), initCodeHash ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves(address tokenA, address tokenB) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IPeanutPair( pairFor(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( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure returns (uint256 amountB) { require(amountA > 0, "PeanutSwapFactory: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "PeanutSwapFactory: 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( uint256 amountIn, uint256 reserveIn, uint256 reserveOut, address token0, address token1 ) public view returns (uint256 amountOut) { require(amountIn > 0, "PeanutSwapFactory: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "PeanutSwapFactory: INSUFFICIENT_LIQUIDITY" ); uint256 fee = getPairFees(pairFor(token0, token1)); uint256 amountInWithFee = amountIn.mul(FEE_RATE_DENOMINATOR.sub(fee)); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(FEE_RATE_DENOMINATOR).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( uint256 amountOut, uint256 reserveIn, uint256 reserveOut, address token0, address token1 ) public view returns (uint256 amountIn) { require(amountOut > 0, "PeanutSwapFactory: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "PeanutSwapFactory: INSUFFICIENT_LIQUIDITY" ); uint256 fee = getPairFees(pairFor(token0, token1)); uint256 numerator = reserveIn.mul(amountOut).mul(FEE_RATE_DENOMINATOR); uint256 denominator = reserveOut.sub(amountOut).mul( FEE_RATE_DENOMINATOR.sub(fee) ); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(uint256 amountIn, address[] memory path) public view returns (uint256[] memory amounts) { require(path.length >= 2, "PeanutSwapFactory: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves( path[i], path[i + 1] ); amounts[i + 1] = getAmountOut( amounts[i], reserveIn, reserveOut, path[i], path[i + 1] ); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(uint256 amountOut, address[] memory path) public view returns (uint256[] memory amounts) { require(path.length >= 2, "PeanutSwapFactory: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves( path[i - 1], path[i] ); amounts[i - 1] = getAmountIn( amounts[i], reserveIn, reserveOut, path[i - 1], path[i] ); } } }
Set default fee ,max is 5%
function setFeeRateNumerator(uint256 _feeRateNumerator) external { require(msg.sender == feeToSetter, "PeanutSwapFactory: FORBIDDEN"); require( _feeRateNumerator <= 500, "PeanutSwapFactory: EXCEEDS_FEE_RATE_DENOMINATOR" ); feeRateNumerator = _feeRateNumerator; }
15,832,424
./partial_match/97/0x1C2b0d8DCf6c39432c721cbcc1d8D88e15907534/sources/BooMaster.sol
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(address _pair) public { UserInfo storage userInfo = poolUserInfoMap[_pair][msg.sender]; IBEP20(_pair).safeTransfer(address(msg.sender), userInfo.amount); emit EmergencyWithdraw(msg.sender, _pair, userInfo.amount); userInfo.amount = 0; userInfo.rewardDebt = 0; }
11,472,740
./partial_match/1/0x665c23A5722B6A237fa6Be2B49c0A94504db1edd/sources/contracts/universal/ProxyAdmin.sol
Returns the admin of the given proxy address. _proxy Address of the proxy to get the admin of. return Address of the admin of the proxy./
function getProxyAdmin(address payable _proxy) external view returns (address) { return IStaticERC1967Proxy(_proxy).admin(); }
4,372,904
./full_match/4/0x1DC826B3712cf9d1D879af8870Cb3E2250f7d495/sources/contracts/TheSouthPark.sol
from null address to , create one new batch ids
function mintTokens(address _to, uint256[] memory _ids) external onlyOwner { uint256 cnt = _ids.length; for (uint256 i = 0; i < cnt; i++) { makeRecord(_to, _ids[i]); } super._mintBatch(_to, _ids, _getAmountArray(cnt), ""); }
12,361,669
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; 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); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } 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); } 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); } } } } 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); _; } } 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; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; 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 = 999900000000000000; 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); } /// @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); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, 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) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { 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; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, 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(); } } 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); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @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); } } } 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; } } 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)"))); } } 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); } } 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); } } } 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(); } } 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, SaverExchangeCore.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); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, 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); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } 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); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { 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; } } 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); } } } 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); } } 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); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_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]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 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[minIndex] && _rates[i] > 0) || _rates[minIndex] == 0) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } 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; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; 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; } } 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]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { 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 claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } 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); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) 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, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) 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); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } 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; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } 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); } 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); } 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); } abstract contract Faucet { function gulp(address) public virtual; } 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; } 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); } 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); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } 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 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); // ---------------- 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 ); } 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); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public view virtual returns(uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } 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); } 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); } 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; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } 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); } 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; } 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); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { 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; } 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); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } 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); } 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; } 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); } } contract MCDMonitorProxyV2 is AdminAuth { 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 _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 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; } } 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; } } 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; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; 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); } } 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); } } } 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)) / (10**27); 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)) / (10**27); 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); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } 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); } 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); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x71eC9a4fCE561c3936a511D9ebb05B60CF2bA519; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; 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( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); 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()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } 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 ManagerLike { 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; } 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 GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } 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; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } 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 ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint 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 SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint 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, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint 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(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint 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 = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint 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, uint wad) public { GemLike(gem).transfer(dst, wad); } 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); } function gemJoin_join(address apt, address urn, uint 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 (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint 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 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint 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 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint 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); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint 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, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint 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, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @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 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(); } } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } 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); } } 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); } } 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); } } 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); } } 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; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ 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; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } 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)))); } } contract LoanShifterTaker is AdminAuth, ProxyPermission { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2612Af3A521c2df9EAF28422Ca335b04AdF3ac66); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; 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( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); uint loanAmount = _loanShift.debtAmount; if (_loanShift.wholeDebt) { loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData); removePermission(loanShifterReceiverAddr); } 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 CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } 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"); } } 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); } } } } 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; } } 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); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } 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}); } } 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: "" }); } } 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] }); } } 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); } } 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); } _; } } 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, 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"); } } } 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; } } 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]; } } 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 variable rate and 2 for fixed 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; } amount += 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; } amount += 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, 0); 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); } } 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 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 price; bool usageAsCollateralEnabled; } /// @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 (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = 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 priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, 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]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; 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 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; } } } 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); } } 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); } } } 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(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x0e49911C937357EAA5a56984483b4B8918D0493b; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,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(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // 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)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, 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)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x2f8ADA783E0696F610e5637CF873B967f47dF2E3; 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 AaveImport 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, msg.sender, 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)); } } 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, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } 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); } } 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 = 2000000; uint public BOOST_GAS_COST = 2000000; 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 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); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; 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; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, 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; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, 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, 0); 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 } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; 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, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound 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(COMPOUND_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); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; 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 COMPOUND_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(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)); } /// @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); } } } 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, msg.value, 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, msg.value, 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(swapedTokens >= 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 _msgValue msg.value in transaction /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _msgValue, uint256 _srcAmount) internal returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return _msgValue; // 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 (_msgValue > _srcAmount) return _msgValue - _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 _msgValue; } 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 {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; 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); 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, WALLET_ID ); 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); 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, WALLET_ID ); 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(); } } 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 {} } 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 {} } 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 {} } 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)); } } 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 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); } 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); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; 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( SaverExchangeCore.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.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (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( SaverExchangeCore.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.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (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; } } } contract MCDCloseFlashLoan is SaverExchangeCore, 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 ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); 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 { ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, _user); } else { dfsFee = getFee(_closeData.daiAmount, _user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); 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(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.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 (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == 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, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); 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; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.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 _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _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, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, 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 ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; 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"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], 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 { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, 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 MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; 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 ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); 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( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // 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, owner, _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( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_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, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.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 _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(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @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(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.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @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(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.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.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @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(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _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); } /// @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 getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _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); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } 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); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2612Af3A521c2df9EAF28422Ca335b04AdF3ac66); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} 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 sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount = getBalance(exchangeData.srcAddr); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(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(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _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 override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getWholeDebt(uint _cdpId, address _joinAddr) public virtual 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); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { 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).transfer(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).transfer(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).transfer(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); } } contract McdShifter is MCDSaverProxy { 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(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { 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(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_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 (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, 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 ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.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 (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, 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()); uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(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(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } 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)); } } 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; } 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]) }); } } /// @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(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // 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 { // Format the call data for DSProxy (address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); // Swap (, uint sellAmount) = _sell(exchangeData); // DFS fee getFee(sellAmount, exchangeData.destAddr, proxyAddr); // Send amount to DSProxy sendToProxy(proxyAddr, exchangeData.destAddr); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(compOpenProxy, 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 (address payable, bytes memory proxyData, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); return (payable(proxy), proxyData, 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); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; 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 {} } contract CompoundSaverFlashProxy is SaverExchangeCore, 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]; (,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, "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 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, "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); } } contract CompoundSaverProxy is CompoundSaverHelper, 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, "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) { 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, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, 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) { // 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 { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, 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; } } 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; } 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 ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); 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 user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.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, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; /// @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)); if (_exData.srcAmount <= maxColl) { 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, "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)); if (_exData.srcAmount <= maxBorrow) { 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, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
Takes token amount from user's wallet and joins into the vat Locks token amount into the CDP
function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { gemJoin_join(gemJoin, address(this), wad, transferFrom); VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); }
7,335,178
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * * @author Rao Nagos * KaveuERC721 - Kaveu - KVU * Repository URL : https://github.com/Kaveu/kaveu-core * Website URL : https://kaveu.io * * Kaveu is a project based on NFTs which are used as a key to be allowed to use an arbitration bot (IA) on CEXs/DEXs. * Each NFT has a basic `claws` to arbitrate 2 tokens on the C/DEXs. The same `claws` can be borrowed from third parties if the owners allows it. */ contract KaveuERC721 is ERC721, ERC721Holder, Ownable, ReentrancyGuard { // Identify who the caller is enum AssignState { DEFAULT, BY_OWNER, BY_BORROWER } /** * @param deadline The loan period * @param totalAmount The price of the loan * @param totalBorrow The total number of claw that were borrowed by {borrower} * @param caller The one who called the function and also who will receive the refunds * @param borrower The dedicated account * @param assignState See above */ struct BorrowData { uint256 deadline; uint256 totalAmount; uint256 totalBorrow; address caller; address borrower; AssignState assignState; } /** * @param pricePerDay The price of the loan per day * @param totalBorrow The total number of claws that were borrowed by all borrowers * @param totalAssign The total number of claws that were assigned by the owner * @param totalClaw The total number of claws * @param priceClaw The price of the claw */ struct Claw { uint256 pricePerDay; uint256 totalBorrow; uint256 totalAssign; uint256 totalClaw; uint256 priceClaw; } // Simple events event ClawLoaning(uint256 indexed tokenId, uint256 indexed pricePerDay); event ClawBorrowed(uint256 indexed tokenId, address indexed borrower, uint256 indexed deadline); // The maximum supply that can be mined uint256 public constant MAX_SUPPLY = 15; // $ echo "(7 * 2) + 1" | bc // The safe address to withdraw or to sell tokens address public safeAddress; // The base uri that stores the json file string private _baseUri; // Map {Claw} by the id of token mapping(uint256 => Claw) private _claws; // Map {BorrowData} by borrower address mapping(uint256 => mapping(address => BorrowData)) private _borrowers; address[] private _borrowerArray; /** * @dev Throws if the token does not exist. * See {ERC721-_exists}. * * @param tokenId The id of the token */ modifier existToken(uint256 tokenId) { require(_exists(tokenId), "KaveuERC721: the token does not exist"); _; } /** * @dev Throws if called by any account other than the owner. * See {IERC721-ownerOf}. * * @param tokenId The id of the token */ modifier onlyOwnerOf(uint256 tokenId) { require(ownerOf(tokenId) == msg.sender, "KaveuERC721: you are not the owner"); _; } /** * @dev Set the {Claw.priceClaw} to 12,7 ether (starting price) and {Claw.totalClaw} to 2. * Set the {_baseUri} and the {safeAddress}. * * @param safeAddress_ The safe address of deployer * @param uri_ The CID of ipfs url */ constructor(address safeAddress_, string memory uri_) ERC721("Kaveu", "KVU") { safeAddress = safeAddress_; _baseUri = uri_; for (uint256 id = 1; id <= MAX_SUPPLY; id++) { _claws[id].totalClaw = id > 1 ? 2 : 7; // The one should never be sold _claws[id].priceClaw = 12.7 gwei; // 12.7 ether (matic): 18$ at april 17th 2022 _mint(safeAddress, id); } } /** * @return MAX_SUPPLY The maximum supply */ function totalSupply() external pure returns (uint256) { return MAX_SUPPLY; } /** * @dev See {IERC721Metadata-tokenURI}. * * @param _tokenId The id of the token * @return uri The uri token of the {_tokenId} */ function tokenURI(uint256 _tokenId) public view virtual override existToken(_tokenId) returns (string memory) { return string(abi.encodePacked(_baseUri, Strings.toString(_tokenId), ".json")); } /** * @dev Call once a time all the tokens uri. * * @return uris All tokens uri */ function getTokenURIs() external view virtual returns (string[] memory) { string[] memory uris = new string[](MAX_SUPPLY); for (uint256 tokenId = 1; tokenId <= MAX_SUPPLY; tokenId++) uris[tokenId - 1] = tokenURI(tokenId); return uris; } /** * @return balance The balance of the contract */ function balance() external view returns (uint256) { return address(this).balance; } /** * @dev Allows the deployer to send the contract balance to the {safeAddress}. */ function withdraw() external virtual onlyOwner nonReentrant { (bool success, ) = payable(safeAddress).call{value: address(this).balance}(""); require(success, "Address: unable to send value"); } /** * @dev Allow the deployer to set the {safeAddress} by the {_safeAddress}. * * @param _safeAddress The new safe address */ function setSafeAddress(address _safeAddress) external virtual onlyOwner { safeAddress = _safeAddress; } /** * @dev Allows the deployer to set the {_baseUri} by the {_newUri}. * * @param _newUri The new {_baseUri} */ function setUri(string memory _newUri) external virtual onlyOwner { _baseUri = _newUri; } /** * @dev Allows the owner to increase claws of the {_tokenId} by {_incBy} by sending a minimum amount. * The {Claw.priceClaw} is updated according to the formula: {Claw.totalClaw} * 5,7614 ether. * !! Decreases claws does not exist. * * Throws if the {_tokenId} is less than 1 and if the {value} is less than the required amount. * * @param _tokenId The id of the token * @param _incBy The number of claws to add */ function increaseClaws(uint256 _tokenId, uint256 _incBy) external payable virtual onlyOwnerOf(_tokenId) nonReentrant { require(msg.value >= _incBy * _claws[_tokenId].priceClaw && _tokenId > 1, "KaveuERC721: unable to increase the token"); _claws[_tokenId].totalClaw += _incBy; _claws[_tokenId].priceClaw = _claws[_tokenId].totalClaw * 5.7614 gwei; // 5,7614 = (12,7 / 7,21) + (7 - 2 - 1) } /** * @dev Allows the deployer to increase by 4, all owner claws except the id one. * This function affects the {increaseClaws} function. */ function airdrop() external virtual onlyOwner { for (uint256 id = 2; id <= MAX_SUPPLY; id++) _claws[id].totalClaw += (7 - 2 - 1); } ///////////////////////////////////////////////////////////////////// /////////////////////////// LOAN //////////////////////////////////// ///////////////////////////////////////////////////////////////////// /** * @param _tokenId The id of the token * @return claw The {Claw} of the {_tokenId} */ function clawsOf(uint256 _tokenId) external view existToken(_tokenId) returns (Claw memory) { return _claws[_tokenId]; } /** * @dev The IA uses this function to check if a borrower is allowed to use him. * * @param _tokenId The id of the token * @return borrowDatas An array of {BorrowData} of the {_tokenId} */ function borrowOf(uint256 _tokenId) external view existToken(_tokenId) returns (BorrowData[] memory) { uint256 ln = _borrowerArray.length; if (ln == 0) return new BorrowData[](ln); uint256 cbsIndex; uint256 i; BorrowData[] memory cbs = new BorrowData[](ln); for (i = 0; i < ln; i++) { BorrowData memory cb = _borrowers[_tokenId][_borrowerArray[i]]; if (cb.assignState != AssignState.DEFAULT) { cbs[cbsIndex] = cb; cbsIndex++; } } // use assembly to decrease the size for null data (by null, it means AssignState.DEFAULT) // the first 'if' above makes the following code safe for (i = cbsIndex; i < ln; i++) assembly { mstore(cbs, sub(mload(cbs), 1)) } return cbs; } /** * ~ON-CHAIN~ * @dev The IA uses this function to check if a borrower is allowed to use him. * Check to see if the borrower exists and if the deadline of the loan has been reached. * * @param _borrower The borrower to find * @return isBorrower */ function isBorrower(address _borrower) external view returns (bool) { bool find = false; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowerArray[i] == _borrower) { find = true; break; } if (!find) return find; for (uint256 id = 1; id <= MAX_SUPPLY; id++) if (_borrowers[id][_borrower].assignState != AssignState.DEFAULT && _borrowers[id][_borrower].deadline > block.timestamp) return true; return false; } /** * ~ON-CHAIN~ * @param _borrower The borrower who borrows * @return totalBorrowsOf The number of claws the {_borrower} borrows. */ function totalBorrowsOf(address _borrower) external view returns (uint256) { uint256 total = 0; for (uint256 id = 1; id <= MAX_SUPPLY; id++) total += _borrowers[id][_borrower].totalBorrow; return total; } /** * @dev Removes {index} borrower from the array by calling the pop() function. * In fine : this will decrease the array length by 1. * * @param index The cute index */ function removeBorrower(uint256 index) private { _borrowerArray[index] = _borrowerArray[_borrowerArray.length - 1]; _borrowerArray.pop(); } /** * @dev Manually assigns a {_borrower} once to the token {_tokenId} for 721 years and without paying the loan fee. * The {_borrower} is a dedicated account. Considere checking the website for more info. * !! The {Claw.assignState} is set by the owner. * * Throws if the {Claw.totalAssign} of the {_tokenId} is greater than the {Claw.totalClaw}. * And throws if the {BorrowData.assignState} of the {_borrower} is not an {AssignState.DEFAULT}. * * This emits the {ClawBorrowed} event. * * @param _tokenId The id of the token * @param _forClaws The number of claws the owner wants to borrow * @param _borrower The address of the borrower */ function assign( uint256 _tokenId, uint256 _forClaws, address _borrower ) external virtual onlyOwnerOf(_tokenId) { BorrowData memory cb = _borrowers[_tokenId][_borrower]; Claw memory cl = _claws[_tokenId]; cl.totalAssign += _forClaws; require(cl.totalAssign <= cl.totalClaw && cb.assignState == AssignState.DEFAULT, "KaveuERC721: cannot assign the borrower"); cb.deadline = block.timestamp + (31536000 * 721); // 31536000 YEAR_IN_SECONDS cb.assignState = AssignState.BY_OWNER; cb.totalBorrow = _forClaws; cb.caller = msg.sender; cb.borrower = _borrower; _claws[_tokenId] = cl; _borrowers[_tokenId][_borrower] = cb; _borrowerArray.push(_borrower); emit ClawBorrowed(_tokenId, _borrower, cb.deadline); } /** * @dev Deassigns a {_borrower} who has already been manually assigned from the assign() function. * If {Claw.totalAssign} is 0, then it will clear the data. * * Throws if the {BorrowData.assignState} was not assigned by the owner. * * @param _tokenId The id of the token * @param _forClaws The number of claws the owner wants to borrow * @param _borrower The address of the borrower */ function deassign( uint256 _tokenId, uint256 _forClaws, address _borrower ) external virtual onlyOwnerOf(_tokenId) { Claw storage cl = _claws[_tokenId]; cl.totalAssign -= _forClaws; // reverting on overflow require(_borrowers[_tokenId][_borrower].assignState == AssignState.BY_OWNER, "KaveuERC721: cannot deassign the borrower"); // clear() if (cl.totalAssign == 0) for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowerArray[i] == _borrower) { delete _borrowers[_tokenId][_borrower]; removeBorrower(i); break; } } /** * @dev Create a loan for the {_tokenId} by setting a price {_pricePerDay}. * To stop the loan, set the {_pricePerDay} to 0 but this does not stop the current rentals. * * This emits {ClawLoaning} event. * * @param _tokenId The id of the token * @param _pricePerDay The price the caller wants to loan claws */ function loan(uint256 _tokenId, uint256 _pricePerDay) external virtual onlyOwnerOf(_tokenId) { _claws[_tokenId].pricePerDay = _pricePerDay; emit ClawLoaning(_tokenId, _pricePerDay); } /** * @dev Create a borrow for a {_tokenId} by sending a minimum amount. Borrow until {_forDays} + {block.timestamp}. * If the owner of the {_tokenId} wants to sell it, he will have to pay back {BorrowData.totalAmount} the {BorrowData.caller} completely first, not for the days remaining. * !! The caller cannot cancel the loan until the deadline is reached. * * See {loan} to stop it. * See {_beforeTokenTransfer} to check the refunds. * * Throws if {Claw.pricePerDay} of the {_tokenId} or {_forDays} is 0. * Throws if the {Claw.totalBorrow} is greater than the {Claw.totalClaw}. * Throws if {BorrowData.assignState} is not an {AssignState.DEFAULT}. * And throws if the {value} is less than the required amount. * * This emits the {ClawBorrowed} event. * * @param _tokenId The id of the token * @param _forClaws The number of claws the caller wants to borrow * @param _forDays The number of days the caller wants to borrow * @param _borrower The address of the borrower */ function borrow( uint256 _tokenId, uint256 _forClaws, uint256 _forDays, address _borrower ) external payable virtual existToken(_tokenId) nonReentrant { Claw memory cl = _claws[_tokenId]; cl.totalBorrow += _forClaws; BorrowData memory cb = _borrowers[_tokenId][_borrower]; require(cl.pricePerDay > 0 && _forClaws > 0 && _forDays > 0 && cl.totalBorrow <= cl.totalClaw && cb.assignState == AssignState.DEFAULT, "KaveuERC721: cannot borrow"); cb.deadline = block.timestamp + (_forDays * 86400); // 86400 DAY_IN_SECONDS cb.totalAmount = _forClaws * _forDays * cl.pricePerDay; cb.totalBorrow = _forClaws; cb.caller = msg.sender; // refund the caller cb.borrower = _borrower; cb.assignState = AssignState.BY_BORROWER; _claws[_tokenId] = cl; _borrowers[_tokenId][_borrower] = cb; _borrowerArray.push(_borrower); // pays loan fee require(msg.value >= cb.totalAmount, "KaveuERC721: not enought token"); (bool success, ) = payable(ownerOf(_tokenId)).call{value: msg.value}(""); require(success, "Address: unable to send value"); emit ClawBorrowed(_tokenId, _borrower, cb.deadline); } /** * @dev Clears the data if the {BorrowData.deadline} has been reached. Anyone can call this function. */ function clear() external virtual { uint256 ln = _borrowerArray.length; uint256[] memory array = new uint256[](ln); uint256 counter = 0; uint256 i; for (uint256 id = 1; id <= MAX_SUPPLY; id++) for (i = 0; i < _borrowerArray.length; i++) { BorrowData memory cb = _borrowers[id][_borrowerArray[i]]; if (cb.assignState != AssignState.DEFAULT && cb.deadline < block.timestamp) { Claw storage cl = _claws[id]; if (cb.assignState == AssignState.BY_OWNER) cl.totalAssign -= cb.totalBorrow; else cl.totalBorrow -= cb.totalBorrow; array[counter] = i; counter++; delete _borrowers[id][_borrowerArray[i]]; } } for (i = 0; i < counter; i++) removeBorrower(array[i]); } /** * @param _tokenId The id of the token * @return amountIn The required amount to refund the owner of the {_tokenId} */ function getAmountInToRefund(uint256 _tokenId) public view returns (uint256) { uint256 amountIn = 0; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[_tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER) amountIn += _borrowers[_tokenId][_borrowerArray[i]].totalAmount; return amountIn; } /** * @dev Check that there are no refunds to be made prior to the transfer. If there is, a refund is required to the `BorrowData.caller` for `BorrowData.totalAmount`, not for the days remaining. * !! It is recommended to call the {clear} function first. * * Throws if the {value} is less than the required amount. * */ function refundBorrowers(uint256 _tokenId) external payable virtual nonReentrant { require(msg.value >= getAmountInToRefund(_tokenId), "KaveuERC721: not enought token"); for (uint256 i = 0; i < _borrowerArray.length; i++) { BorrowData memory cb = _borrowers[_tokenId][_borrowerArray[i]]; if (cb.assignState == AssignState.BY_BORROWER) { // refunds the caller (bool success, ) = payable(cb.caller).call{value: cb.totalAmount}(""); require(success, "Address: unable to send value"); // to clear() cb.deadline = block.timestamp - 10; _borrowers[_tokenId][_borrowerArray[i]] = cb; } } } /** * See {ERC721-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); // from _mint() or to _burn() if (from == address(0) || to == address(0)) return; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER && _borrowers[tokenId][_borrowerArray[i]].deadline > block.timestamp) revert("KaveuERC721: refund borrowers first"); } }
See {ERC721-_beforeTokenTransfer}./ from _mint() or to _burn()
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0) || to == address(0)) return; for (uint256 i = 0; i < _borrowerArray.length; i++) if (_borrowers[tokenId][_borrowerArray[i]].assignState == AssignState.BY_BORROWER && _borrowers[tokenId][_borrowerArray[i]].deadline > block.timestamp) revert("KaveuERC721: refund borrowers first"); }
15,811,883
./partial_match/1/0x202c1d54f2885C54aaC50d9651367011Be6Fc01b/sources/src/ChadGame.sol
Set cooldown needed to win
function setCooldown(uint256 _cooldown) external onlyOwner { require(_cooldown > 60, "Cooldown must be greater than 60 seconds"); cooldown = _cooldown; }
2,849,209
./full_match/5/0x9055F4e28C4679262F2Bbb87f97FC5B4DAF52aE0/sources/contracts/Crowdfunding.sol
payable: sigifies that there is cryptoexchange throughout the function arrays are for donators and donations
function getDonators(uint256 _id) view public returns (address[] memory, uint256[] memory){ return( campaigns[_id].donators, campaigns[_id].donations); }
1,851,967
/** *Submitted for verification at Etherscan.io on 2022-04-18 */ pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/math/SafeCast.sol pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: @openzeppelin/contracts/utils/math/SignedSafeMath.sol pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. 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; } } } // File: @openzeppelin/contracts-upgradeable/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. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 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; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // File: Farm.sol pragma solidity 0.8.0; pragma experimental ABIEncoderV2; contract BTE_LPStaking is Initializable, OwnableUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SignedSafeMath for int256; using SafeCast for int256; /// @notice Info of each user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of reward entitled to the user. /// `lastDepositedAt` The timestamp of the last deposit. struct UserInfo { uint256 amount; int256 rewardDebt; uint256 lastDepositedAt; } uint256 private constant ACC_REWARD_PRECISION = 1e12; /// @notice Address of reward contract. IERC20 public reward; /// @notice Address of the LP token. IERC20 public lpToken; /// @notice reward amount allocated per LP token. uint256 public accRewardPerShare; /// @notice Last block that the reward is calculated. uint256 public lastRewardBlock; /// @notice reward Per Block. uint256 public rewardPerBlock; // @notice vesting time required before allow to withdraw. uint256 public vestingTime = 30 days; /// @notice Info of each user that stakes LP tokens. mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 amount, address indexed to); event EmergencyWithdraw( address indexed user, uint256 amount, address indexed to ); event Harvest(address indexed user, uint256 amount); event LogUpdatePool( uint256 lastRewardBlock, uint256 lpSupply, uint256 accRewardPerShare ); /** * @param _reward The reward token contract address. * @param _lpToken The staking contract address. */ function initialize(IERC20 _reward, IERC20 _lpToken) external initializer { __Ownable_init(); reward = _reward; lpToken = _lpToken; accRewardPerShare = 0; lastRewardBlock = block.number; } /** * @notice Sets the reward per block to be distributed. Can only be called by the owner. * @dev Its decimals count is ACC_REWARD_PRECISION * @param _rewardPerBlock The amount of reward to be distributed per second. */ function setRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { updatePool(); rewardPerBlock = _rewardPerBlock; } /** * @notice View function to see pending reward on frontend. * @dev It doens't update accRewardPerShare, it's just a view function. * @param _user Address of user. * @return pending reward for a given user. */ function pendingReward(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 lpSupply = lpToken.balanceOf(address(this)); uint256 accRewardPerShare_ = accRewardPerShare; if (block.number > lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(lastRewardBlock); uint256 blockReward = blocks.mul(rewardPerBlock); accRewardPerShare_ = accRewardPerShare_.add( blockReward.mul(ACC_REWARD_PRECISION) / lpSupply ); } pending = int256( user.amount.mul(accRewardPerShare_) / ACC_REWARD_PRECISION ).sub(user.rewardDebt).toUint256(); } /** * @notice Update reward variables. * @dev Updates accRewardPerShare and lastRewardBlock. */ function updatePool() public { if (block.number > lastRewardBlock) { uint256 lpSupply = lpToken.balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(lastRewardBlock); uint256 blockReward = blocks.mul(rewardPerBlock); accRewardPerShare = accRewardPerShare.add( blockReward.mul(ACC_REWARD_PRECISION) / lpSupply ); } lastRewardBlock = block.number; emit LogUpdatePool(lastRewardBlock, lpSupply, accRewardPerShare); } } /** * @notice Deposit LP tokens for reward allocation. * @param amount LP token amount to deposit. * @param to The receiver of `amount` deposit benefit. */ function deposit(uint256 amount, address to) public { updatePool(); UserInfo storage user = userInfo[to]; // Effects user.lastDepositedAt = block.timestamp; user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add( int256(amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION) ); lpToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount, to); } /** * @notice Withdraw LP tokens and harvest rewards to `to`. * @param amount LP token amount to withdraw. * @param to Receiver of the LP tokens and rewards. */ function withdraw(uint256 amount, address to) public { updatePool(); UserInfo storage user = userInfo[msg.sender]; require(block.timestamp >= user.lastDepositedAt.add(vestingTime), "Vesting time requires!"); int256 accumulatedReward = int256( user.amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION ); uint256 _pendingReward = accumulatedReward .sub(user.rewardDebt) .toUint256(); // Effects user.rewardDebt = accumulatedReward.sub( int256(amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION) ); user.amount = user.amount.sub(amount); reward.safeTransfer(to, _pendingReward); lpToken.safeTransfer(to, amount); emit Withdraw(msg.sender, amount, to); emit Harvest(msg.sender, _pendingReward); } /** * @notice Harvest rewards and send to `to`. * @dev Here comes the formula to calculate reward token amount * @param to Receiver of rewards. */ function harvest(address to) public { updatePool(); UserInfo storage user = userInfo[msg.sender]; int256 accumulatedReward = int256( user.amount.mul(accRewardPerShare) / ACC_REWARD_PRECISION ); uint256 _pendingReward = accumulatedReward .sub(user.rewardDebt) .toUint256(); // Effects user.rewardDebt = accumulatedReward; // Interactions if (_pendingReward != 0) { reward.safeTransfer(to, _pendingReward); } emit Harvest(msg.sender, _pendingReward); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param to Receiver of the LP tokens. */ function emergencyWithdraw(address to) public { UserInfo storage user = userInfo[msg.sender]; require(block.timestamp >= user.lastDepositedAt.add(vestingTime), "Vesting time requires!"); uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; // Note: transfer can fail or succeed if `amount` is zero. lpToken.safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, amount, to); } /** * @notice deposit reward * @param amount to deposit */ function depositReward(uint256 amount) external onlyOwner { reward.safeTransferFrom(msg.sender, address(this), amount); } /** * @notice withdraw reward * @param amount to withdraw */ function withdrawReward(uint256 amount) external onlyOwner { reward.safeTransfer(msg.sender, amount); } function updateVestingTime(uint256 priodInSecond) external onlyOwner { vestingTime = priodInSecond; } }
Withdraw without caring about rewards. EMERGENCY ONLY. to Receiver of the LP tokens./ Note: transfer can fail or succeed if `amount` is zero.
function emergencyWithdraw(address to) public { UserInfo storage user = userInfo[msg.sender]; require(block.timestamp >= user.lastDepositedAt.add(vestingTime), "Vesting time requires!"); uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; lpToken.safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, amount, to); }
15,109,371
// SPDX-License-Identifier: MIT pragma solidity >0.7.5; pragma experimental ABIEncoderV2; /** * @title iL1LiquidityPool */ interface iL1LiquidityPool { /******************** * Events * ********************/ event AddLiquidity( address sender, uint256 amount, address tokenAddress ); event OwnerRecoverFee( address sender, address receiver, uint256 amount, address tokenAddress ); event ClientDepositL1( address sender, uint256 receivedAmount, address tokenAddress ); event ClientPayL1( address sender, uint256 amount, uint256 userRewardFee, uint256 ownerRewardFee, uint256 totalFee, address tokenAddress ); event ClientPayL1Settlement( address sender, uint256 amount, uint256 userRewardFee, uint256 ownerRewardFee, uint256 totalFee, address tokenAddress ); event WithdrawLiquidity( address sender, address receiver, uint256 amount, address tokenAddress ); event WithdrawReward( address sender, address receiver, uint256 amount, address tokenAddress ); /************************* * Cross-chain Functions * *************************/ function clientPayL1( address payable _to, uint256 _amount, address _tokenAddress ) external; function clientPayL1Settlement( address payable _to, uint256 _amount, address _tokenAddress ) external; function configureFee( uint256 _userRewardFeeRate, uint256 _ownerRewardFeeRate ) external; }
iL1LiquidityPool/
interface iL1LiquidityPool { event AddLiquidity( address sender, uint256 amount, address tokenAddress ); event OwnerRecoverFee( address sender, address receiver, uint256 amount, address tokenAddress ); event ClientDepositL1( address sender, uint256 receivedAmount, address tokenAddress ); event ClientPayL1( address sender, uint256 amount, uint256 userRewardFee, uint256 ownerRewardFee, uint256 totalFee, address tokenAddress ); event ClientPayL1Settlement( address sender, uint256 amount, uint256 userRewardFee, uint256 ownerRewardFee, uint256 totalFee, address tokenAddress ); event WithdrawLiquidity( address sender, address receiver, uint256 amount, address tokenAddress ); event WithdrawReward( address sender, address receiver, uint256 amount, address tokenAddress ); function clientPayL1( address payable _to, uint256 _amount, address _tokenAddress ) external; function clientPayL1Settlement( address payable _to, uint256 _amount, address _tokenAddress ) external; function configureFee( uint256 _userRewardFeeRate, uint256 _ownerRewardFeeRate ) external; pragma solidity >0.7.5; }
980,699
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./Ownable.sol"; contract Wallet is Ownable { event DepositCompleted(address from, uint amount); event TransferRequestCreated(uint txId, uint amount, address recipient, address requestedBy); event TransderRequestApproved(uint txId, address approver); event TransderRequestCompleted(uint txId, uint amount, address recipient); uint8 private requiredApprovals; uint private txCount; struct TransferRequest { uint txId; uint amount; address recipient; mapping(address => bool) signatures; address requestedBy; uint8 approvals; } mapping(uint => TransferRequest) public requestedTransfers; /** * @dev one of the owners would be msg.sender during contract deployment */ constructor(address[] memory _owners) Ownable(_owners) { requiredApprovals = uint8(_owners.length); } /** * @dev Deposit function. Along with the fallback function anyone can send funds to the contract */ function deposit() external payable { emit DepositCompleted(msg.sender, msg.value); } receive() external payable { emit DepositCompleted(msg.sender, msg.value); } /** * @dev Requesting the transfer for approval */ function requestTransfer(address _recipient, uint _amount) public onlyOwners returns (uint) { require(_amount <= address(this).balance, "Insufficient funds in the contract"); TransferRequest storage txRequest = requestedTransfers[txCount]; txRequest.txId = txCount; txRequest.amount = _amount; txRequest.recipient = _recipient; txRequest.requestedBy = msg.sender; emit TransferRequestCreated(txCount, _amount, _recipient, msg.sender); return txCount++; } /** * @dev Handles the approval of the transfer request. Only the owner of the wallet can approve. */ function approveTransfer(uint _txId) public onlyOwners { TransferRequest storage txRequest = requestedTransfers[_txId]; require(txRequest.requestedBy != msg.sender, "You can't approve your own transfer request"); require(!txRequest.signatures[msg.sender], "You already approved this transder request"); txRequest.signatures[msg.sender] = true; txRequest.approvals++; emit TransderRequestApproved(txRequest.txId, msg.sender); if(txRequest.approvals == requiredApprovals) { completeTransfer(txRequest.txId); } } /** * @dev Internal function to complete the requested transfer. This can only be called during the final approval vote * or when retrying due to Insufficient funds in the contract */ function completeTransfer(uint _txId) internal { TransferRequest storage txRequest = requestedTransfers[_txId]; require(txRequest.approvals == requiredApprovals, "Transfer not approved by all required parties."); require(txRequest.amount <= address(this).balance, "Insufficient funds in the contract"); payable(txRequest.recipient).transfer(txRequest.amount); emit TransderRequestCompleted(txRequest.txId, txRequest.amount, txRequest.recipient); } }
Handles the approval of the transfer request. Only the owner of the wallet can approve./
function approveTransfer(uint _txId) public onlyOwners { TransferRequest storage txRequest = requestedTransfers[_txId]; require(txRequest.requestedBy != msg.sender, "You can't approve your own transfer request"); require(!txRequest.signatures[msg.sender], "You already approved this transder request"); txRequest.signatures[msg.sender] = true; txRequest.approvals++; emit TransderRequestApproved(txRequest.txId, msg.sender); if(txRequest.approvals == requiredApprovals) { completeTransfer(txRequest.txId); } }
13,045,314
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { 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 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 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 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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]{20}) is missing role (0x[0-9a-f]{32})$/ */ 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 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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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) { 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.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT 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 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 pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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) { 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.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; struct RoleData { mapping(address => bool) members; bytes32 adminRole; } library AccessControlEvents { event OwnerSet(address indexed owner); event OwnerTransferred(address indexed owner, address indexed prevOwner); /** * @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 ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../storage/roles.sol"; abstract contract int_hasRole_AccessControl_v1 is sto_AccessControl_Roles { function _hasRole(bytes32 role, address account) internal view returns (bool hasRole_) { hasRole_ = accessControlRolesStore().roles[role].members[account]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./has-role.sol"; abstract contract int_requireAuthorization_AccessControl_v1 is int_hasRole_AccessControl_v1 { function _requireAuthorization(bytes32 role, address account) internal view { require(_hasRole(role, account), "AccessControl: unauthorized"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { int_requireAuthorization_AccessControl_v1 } from "../internal/require-authorization.sol"; abstract contract mod_authorized_AccessControl_v1 is int_requireAuthorization_AccessControl_v1 { modifier authorized(bytes32 role, address account) { _requireAuthorization(role, account); _; } } abstract contract mod_authorized_AccessControl is mod_authorized_AccessControl_v1 {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { RoleData } from "../data.sol"; contract sto_AccessControl_Roles { bytes32 internal constant POS = keccak256("teller_protocol.storage.access_control.roles"); struct AccessControlRolesStorage { mapping(bytes32 => RoleData) roles; } function accessControlRolesStore() internal pure returns (AccessControlRolesStorage storage s) { bytes32 position = POS; assembly { s.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IStakeableNFT { function tokenBaseLoanSize(uint256 tokenId) external view returns (uint256); function tokenURIHash(uint256 tokenId) external view returns (string memory); function tokenContributionAsset(uint256 tokenId) external view returns (address); function tokenContributionSize(uint256 tokenId) external view returns (uint256); function tokenContributionMultiplier(uint256 tokenId) external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; // Interfaces import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface ITellerNFT { struct Tier { uint256 baseLoanSize; string[] hashes; address contributionAsset; uint256 contributionSize; uint8 contributionMultiplier; } /** * @notice The contract metadata URI. * @return the contractURI in string */ function contractURI() external view returns (string memory); /** * @notice It returns information about a Tier with from a tier index * @param index Tier index to get info. * @return tier_ the tier which belongs to the respective index */ function getTier(uint256 index) external view returns (Tier memory tier_); /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. * @return index_ the index of the tier the tokenID belongs in * @return tier_ the tier where the tokenID belongs in */ function getTokenTier(uint256 tokenId) external view returns (uint256 index_, Tier memory tier_); /** * @notice It returns an array of hashes in a tier * @param tierIndex the tier index to get the tier hashes * @return hashes_ all the tokenID hashes */ function getTierHashes(uint256 tierIndex) external view returns (string[] memory hashes_); /** * @notice It returns an array of token IDs owned by an address. * @dev It uses a EnumerableSet to store values and loops over each element to add to the array. * @dev Can be costly if calling within a contract for address with many tokens. * @return owned the array of tokenIDs owned by the address */ function getOwnedTokens(address owner) external view returns (uint256[] memory owned); /** * @notice It mints a new token for a Tier index. * @param tierIndex the tier index to mint the token in * @param owner the owner of the new token * Requirements: * - Caller must be an authorized minter */ function mint(uint256 tierIndex, address owner) external; /** * @notice Adds a new Tier to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTier Information about the new tier to add. * * Requirements: * - Caller must have the {MINTER} role */ function addTier(Tier memory newTier) external; /** * @notice Sets the contract level metadata URI hash. * @param contractURIHash The hash to the initial contract level metadata. */ function setContractURIHash(string memory contractURIHash) external; /** * @notice Initializes the TellerNFT. * @param minters The addresses that should allowed to mint tokens. */ function initialize(address[] calldata minters) external; } /** * @notice TellerNFTDictionary Version 1.02 * * @notice This contract is used to gather data for TellerV1 NFTs more efficiently. * @notice This contract has data which must be continuously synchronized with the TellerV1 NFT data * * @author [email protected] */ pragma solidity ^0.8.0; // Contracts import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Interfaces import "./IStakeableNFT.sol"; /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ contract TellerNFTDictionary is IStakeableNFT, AccessControlUpgradeable { struct Tier { uint256 baseLoanSize; string[] hashes; address contributionAsset; uint256 contributionSize; uint8 contributionMultiplier; } mapping(uint256 => uint256) public baseLoanSizes; mapping(uint256 => string[]) public hashes; mapping(uint256 => address) public contributionAssets; mapping(uint256 => uint256) public contributionSizes; mapping(uint256 => uint8) public contributionMultipliers; /* Constants */ bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ mapping(uint256 => uint256) public _tokenTierMappingCompressed; bool public _tokenTierMappingCompressedSet; /* Modifiers */ modifier onlyAdmin() { require(hasRole(ADMIN, _msgSender()), "TellerNFTDictionary: not admin"); _; } function initialize(address initialAdmin) public { _setupRole(ADMIN, initialAdmin); _setRoleAdmin(ADMIN, ADMIN); __AccessControl_init(); } /* External Functions */ /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. */ function getTokenTierIndex(uint256 tokenId) public view returns (uint8 index_) { //32 * 8 = 256 - each uint256 holds the data of 32 tokens . 8 bits each. uint256 mappingIndex = tokenId / 32; uint256 compressedRegister = _tokenTierMappingCompressed[mappingIndex]; //use 31 instead of 32 to account for the '0x' in the start. //the '31 -' reverses our bytes order which is necessary uint256 offset = ((31 - (tokenId % 32)) * 8); uint8 tierIndex = uint8((compressedRegister >> offset)); return tierIndex; } function getTierHashes(uint256 tierIndex) external view returns (string[] memory) { return hashes[tierIndex]; } /** * @notice Adds a new Tier to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTier Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTier(uint256 index, Tier memory newTier) external onlyAdmin returns (bool) { baseLoanSizes[index] = newTier.baseLoanSize; hashes[index] = newTier.hashes; contributionAssets[index] = newTier.contributionAsset; contributionSizes[index] = newTier.contributionSize; contributionMultipliers[index] = newTier.contributionMultiplier; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param tiersMapping Information about the new tiers to add. * * Requirements: * - Caller must have the {Admin} role */ function setAllTokenTierMappings(uint256[] memory tiersMapping) public onlyAdmin returns (bool) { require( !_tokenTierMappingCompressedSet, "TellerNFTDictionary: token tier mapping already set" ); for (uint256 i = 0; i < tiersMapping.length; i++) { _tokenTierMappingCompressed[i] = tiersMapping[i]; } _tokenTierMappingCompressedSet = true; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param index the mapping row, each holds data for 32 tokens * @param tierMapping Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierMapping(uint256 index, uint256 tierMapping) public onlyAdmin returns (bool) { _tokenTierMappingCompressed[index] = tierMapping; return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenIds the NFT token Ids for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenIds( uint256[] calldata tokenIds, uint256 tokenTier ) public onlyAdmin returns (bool) { for (uint256 i; i < tokenIds.length; i++) { setTokenTierForTokenId(tokenIds[i], tokenTier); } return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenId the NFT token Id for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenId(uint256 tokenId, uint256 tokenTier) public onlyAdmin returns (bool) { uint256 mappingIndex = tokenId / 32; uint256 existingRegister = _tokenTierMappingCompressed[mappingIndex]; uint256 offset = ((31 - (tokenId % 32)) * 8); uint256 updateMaskShifted = 0x00000000000000000000000000000000000000000000000000000000000000FF << offset; uint256 updateMaskShiftedNegated = ~updateMaskShifted; uint256 tokenTierShifted = ((0x0000000000000000000000000000000000000000000000000000000000000000 | tokenTier) << offset); uint256 existingRegisterClearedWithMask = existingRegister & updateMaskShiftedNegated; uint256 updatedRegister = existingRegisterClearedWithMask | tokenTierShifted; _tokenTierMappingCompressed[mappingIndex] = updatedRegister; return true; } function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return interfaceId == type(IStakeableNFT).interfaceId || AccessControlUpgradeable.supportsInterface(interfaceId); } /** New methods for the dictionary */ /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return baseLoanSizes[tokenTier]; } /** * @notice It returns Token URI Hash for a token ID. * @param tokenId ID of the token to get info. */ function tokenURIHash(uint256 tokenId) public view override returns (string memory) { uint8 tokenTier = getTokenTierIndex(tokenId); string[] memory tierImageHashes = hashes[tokenTier]; return tierImageHashes[tokenId % (tierImageHashes.length)]; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view override returns (address) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionAssets[tokenTier]; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionSizes[tokenTier]; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view override returns (uint8) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionMultipliers[tokenTier]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; bytes32 constant ADMIN = keccak256("ADMIN"); bytes32 constant MINTER = keccak256("MINTER"); struct MerkleRoot { bytes32 merkleRoot; uint256 tierIndex; } struct ClaimNFTRequest { uint256 merkleIndex; uint256 nodeIndex; uint256 amount; bytes32[] merkleProof; } library DistributorEvents { event Claimed(address indexed account); event MerkleAdded(uint256 index); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import "../store.sol"; import "../../../contexts/access-control/modifiers/authorized.sol"; import "../internal/distributor.sol"; // Utils import { ClaimNFTRequest, ADMIN, DistributorEvents } from "../data.sol"; contract ent_claim_NFTDistributor_v1 is sto_NFTDistributor, int_distributor_NFT_v1, mod_authorized_AccessControl_v1 { /** * @notice Claims TellerNFTs for a given verifiable merkle proofs for each tier. * @param account The address to claim NFTs on behalf. * @param requests An array requests data generated from the merkle tree. * * Requirements: * - Node in the merkle root must not be claimed already * - Proof of the node must match the merkle tree */ function claim(address account, ClaimNFTRequest[] calldata requests) external { for (uint256 i; i < requests.length; i++) { require( !_isClaimed(requests[i].merkleIndex, requests[i].nodeIndex), "TellerNFT Distributor: already claimed" ); require( _verifyProof(account, requests[i]), "TellerNFT Distributor: invalid proof" ); // Mark it claimed and send the token. _setClaimed(requests[i].merkleIndex, requests[i].nodeIndex); uint256 tierIndex = distributorStore().merkleRoots[requests[i].merkleIndex] .tierIndex; for (uint256 j; j < requests[i].amount; j++) { distributorStore().nft.mint(tierIndex, account); } //Find the newly minted tokens and add to memory uint256[] memory postOwnedTokens = distributorStore().nft.getOwnedTokens(account); uint256[] memory newlyMintedTokenIds = new uint256[](requests[i].amount); uint256 offset = postOwnedTokens.length - requests[i].amount; for (uint256 k; k < requests[i].amount; k++) { newlyMintedTokenIds[k] = postOwnedTokens[k + offset]; } //For each newly minted token, set the tier index in the Dictionary contract distributorStore().dictionary.setTokenTierForTokenIds( newlyMintedTokenIds, tierIndex ); } emit DistributorEvents.Claimed(account); } function setNFTDictionaryAddress(address dictionary) external authorized(ADMIN, msg.sender) { distributorStore().dictionary = TellerNFTDictionary(dictionary); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import "../store.sol"; // Libraries import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; // Utils import { ClaimNFTRequest } from "../data.sol"; contract int_distributor_NFT_v1 is sto_NFTDistributor { /** * @notice It checks the merkle root for a tier if it has already been claimed. * @param merkleIndex Index of the tier. * @param nodeIndex Index of the node in the merkle root. */ function _setClaimed(uint256 merkleIndex, uint256 nodeIndex) internal { uint256 claimedWordIndex = nodeIndex / 256; uint256 claimedBitIndex = nodeIndex % 256; distributorStore().claimedBitMap[merkleIndex][claimedWordIndex] = distributorStore().claimedBitMap[merkleIndex][claimedWordIndex] | (1 << claimedBitIndex); } /** * @notice It checks the merkle root for a tier if it has already been claimed. * @param merkleIndex Index of the tier. * @param nodeIndex Index of the node in the merkle root. * @return claimed_ returns a boolean to check if the tier has already been claimed */ function _isClaimed(uint256 merkleIndex, uint256 nodeIndex) internal view returns (bool) { uint256 claimedWordIndex = nodeIndex / 256; uint256 claimedBitIndex = nodeIndex % 256; uint256 claimedWord = distributorStore().claimedBitMap[merkleIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice it verifies the request's merkle proof with the merkle root in order to claim an NFT * @param account the account's address to be hashed and verified with the claim * @param request the request with the merkle proof to verify */ function _verifyProof(address account, ClaimNFTRequest memory request) internal view returns (bool verified) { verified = MerkleProof.verify( request.merkleProof, distributorStore().merkleRoots[request.merkleIndex].merkleRoot, keccak256( abi.encodePacked(request.nodeIndex, account, request.amount) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Interfaces import "../ITellerNFT.sol"; import "../TellerNFTDictionary.sol"; // Utils import { MerkleRoot } from "./data.sol"; abstract contract sto_NFTDistributor { struct DistributorStorage { ITellerNFT nft; MerkleRoot[] merkleRoots; mapping(uint256 => mapping(uint256 => uint256)) claimedBitMap; TellerNFTDictionary dictionary; } bytes32 constant POSITION = keccak256("teller_nft.distributor"); function distributorStore() internal pure returns (DistributorStorage storage s) { bytes32 P = POSITION; assembly { s.slot := P } } }
Sets the tiers for each tokenId using compressed data. tiersMapping Information about the new tiers to add. Requirements: - Caller must have the {Admin} role/
function setAllTokenTierMappings(uint256[] memory tiersMapping) public onlyAdmin returns (bool) { require( !_tokenTierMappingCompressedSet, "TellerNFTDictionary: token tier mapping already set" ); for (uint256 i = 0; i < tiersMapping.length; i++) { _tokenTierMappingCompressed[i] = tiersMapping[i]; } _tokenTierMappingCompressedSet = true; return true; }
302,853
./partial_match/1/0xE20EF3dcD01DA02ee50FA0b919931F8dFADDE46c/sources/ERC20.sol
before minting new coins, it goes through a “freezing” time / cooling off period. 'require(amount <= (_maxSupply / 5));' checks if the amount of coins to be created is less or greater than 5% of the total supply. 'require(time >= 7);' puts a limit so that that the variable ‘time’ needs to be equal or greater than 7. '_locktime = now + (time 86400);' adds to the Variable ‘_locktime’ the current time + the time calculation. This calculation is done by 'time 86400' , which means that the value inputted will be multiplied by 86400, since the variable 'now' brings values in seconds. Therefore, if the variable ‘time’ receives 7, it will be multiplied by 86400. In conclusion, in case the value of 'time' is equal to 7, there will be a “freezing time / cooling off period” until new tokens can be minted again. ' _nownow = now;' stores in the variable ‘_nownow’ the actual time that the variable ‘now’ entered in the moment that it was used in the calculations above, and can be used as a comparison between the variable '_nownow’ and '_locktime’. '_amountt = amount (10 5);' saves in the variable ‘_amountt’ the amount of tokens that will be minted. This calculation is used in the next function. 'amountMint = amount;’ saves in the variable ‘amountMint’ the amount of tokens that will be minted. This variable is public./
function minttocome(uint256 time, uint256 amount) public virtual onlyOwner { _previousOwner = _msgSender(); _amountt = amount * (10 ** 5); require(_amountt <= (_maxSupply / 5)); require(time >= 7); _locktime = now + (time * 86400); _nownow = now; amountMint = amount; }
4,054,100
pragma solidity ^0.4.8; // accepted from zeppelin-solidity https://github.com/OpenZeppelin/zeppelin-solidity /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // accepted from zeppelin-solidity https://github.com/OpenZeppelin/zeppelin-solidity /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { // flag to determine if address is for a real contract or not bool public isMultiSigWallet = false; uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { if (msg.sender != address(this)) throw; _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) throw; _; } modifier ownerExists(address owner) { if (!isOwner[owner]) throw; _; } modifier transactionExists(uint transactionId) { if (transactions[transactionId].destination == 0) throw; _; } modifier confirmed(uint transactionId, address owner) { if (!confirmations[transactionId][owner]) throw; _; } modifier notConfirmed(uint transactionId, address owner) { if (confirmations[transactionId][owner]) throw; _; } modifier notExecuted(uint transactionId) { if (transactions[transactionId].executed) throw; _; } modifier notNull(address _address) { if (_address == 0) throw; _; } modifier validRequirement(uint ownerCount, uint _required) { if (ownerCount > MAX_OWNER_COUNT) throw; if (_required > ownerCount) throw; if (_required == 0) throw; if (ownerCount == 0) throw; _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == 0) throw; isOwner[_owners[i]] = true; } isMultiSigWallet = true; owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. /// @param index the indx of the owner to be replaced function replaceOwnerIndexed(address owner, address newOwner, uint index) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { if (owners[index] != owner) throw; owners[index] = newOwner; isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) internal notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction tx = transactions[transactionId]; tx.executed = true; if (tx.destination.call.value(tx.value)(tx.data)) Execution(transactionId); else { ExecutionFailure(transactionId); tx.executed = false; } } } /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } contract UpgradeAgent is SafeMath { address public owner; bool public isUpgradeAgent; function upgradeFrom(address _from, uint256 _value) public; function finalizeUpgrade() public; function setOriginalSupply() public; } /// @title Time-locked vault of tokens allocated to DecentBet after 365 days contract DecentBetVault is SafeMath { // flag to determine if address is for a real contract or not bool public isDecentBetVault = false; DecentBetToken decentBetToken; address decentBetMultisig; uint256 unlockedAtTime; // smaller lock for testing uint256 public constant timeOffset = 1 years; /// @notice Constructor function sets the DecentBet Multisig address and /// total number of locked tokens to transfer function DecentBetVault(address _decentBetMultisig) /** internal */ { if (_decentBetMultisig == 0x0) throw; decentBetToken = DecentBetToken(msg.sender); decentBetMultisig = _decentBetMultisig; isDecentBetVault = true; // 1 year later unlockedAtTime = safeAdd(getTime(), timeOffset); } /// @notice Transfer locked tokens to Decent.bet's multisig wallet function unlock() external { // Wait your turn! if (getTime() < unlockedAtTime) throw; // Will fail if allocation (and therefore toTransfer) is 0. if (!decentBetToken.transfer(decentBetMultisig, decentBetToken.balanceOf(this))) throw; } function getTime() internal returns (uint256) { return now; } // disallow ETH payments to TimeVault function() payable { throw; } } /// @title DecentBet crowdsale contract contract DecentBetToken is SafeMath, ERC20 { // flag to determine if address is for a real contract or not bool public isDecentBetToken = false; // State machine enum State{Waiting, PreSale, CommunitySale, PublicSale, Success} // Token information string public constant name = "Decent.Bet Token"; string public constant symbol = "DBET"; uint256 public constant decimals = 18; // decimal places uint256 public constant housePercentOfTotal = 10; uint256 public constant vaultPercentOfTotal = 18; uint256 public constant bountyPercentOfTotal = 2; uint256 public constant crowdfundPercentOfTotal = 70; uint256 public constant hundredPercent = 100; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; // Authorized addresses address public team; // Upgrade information bool public finalizedUpgrade = false; address public upgradeMaster; UpgradeAgent public upgradeAgent; uint256 public totalUpgraded; // Crowdsale information bool public finalizedCrowdfunding = false; // Whitelisted addresses for pre-sale address[] public preSaleWhitelist; mapping (address => bool) public preSaleAllowed; // Whitelisted addresses from community address[] public communitySaleWhitelist; mapping (address => bool) public communitySaleAllowed; uint[2] public communitySaleCap = [100000 ether, 200000 ether]; mapping (address => uint[2]) communitySalePurchases; uint256 public preSaleStartTime; // Pre-sale start block timestamp uint256 public fundingStartTime; // crowdsale start block timestamp uint256 public fundingEndTime; // crowdsale end block timestamp // DBET:ETH exchange rate - Needs to be updated at time of ICO. // Price of ETH/0.125. For example: If ETH/USD = 300, it would be 2400 DBETs per ETH. uint256 public baseTokensPerEther; uint256 public tokenCreationMax = safeMul(250000 ether, 1000); // A maximum of 250M DBETs can be minted during ICO. // Amount of tokens alloted to pre-sale investors. uint256 public preSaleAllotment; // Address of pre-sale investors. address public preSaleAddress; // for testing on testnet //uint256 public constant tokenCreationMax = safeMul(10 ether, baseTokensPerEther); //uint256 public constant tokenCreationMin = safeMul(3 ether, baseTokensPerEther); address public decentBetMultisig; DecentBetVault public timeVault; // DecentBet's time-locked vault event Upgrade(address indexed _from, address indexed _to, uint256 _value); event UpgradeFinalized(address sender, address upgradeAgent); event UpgradeAgentSet(address agent); // Allow only the team address to continue modifier onlyTeam() { if(msg.sender != team) throw; _; } function DecentBetToken(address _decentBetMultisig, address _upgradeMaster, address _team, uint256 _baseTokensPerEther, uint256 _fundingStartTime, uint256 _fundingEndTime) { if (_decentBetMultisig == 0) throw; if (_team == 0) throw; if (_upgradeMaster == 0) throw; if (_baseTokensPerEther == 0) throw; // For testing/dev // if(_fundingStartTime == 0) throw; // Crowdsale can only officially start during/after the current block timestamp. if (_fundingStartTime < getTime()) throw; if (_fundingEndTime <= _fundingStartTime) throw; isDecentBetToken = true; upgradeMaster = _upgradeMaster; team = _team; baseTokensPerEther = _baseTokensPerEther; preSaleStartTime = _fundingStartTime - 1 days; fundingStartTime = _fundingStartTime; fundingEndTime = _fundingEndTime; // Pre-sale issuance from pre-sale contract // 0x7be601aab2f40cc23653965749b84e5cb8cfda43 preSaleAddress = 0x87f7beeda96216ec2a325e417a45ed262495686b; preSaleAllotment = 45000000 ether; balances[preSaleAddress] = preSaleAllotment; totalSupply = safeAdd(totalSupply, preSaleAllotment); timeVault = new DecentBetVault(_decentBetMultisig); if (!timeVault.isDecentBetVault()) throw; decentBetMultisig = _decentBetMultisig; if (!MultiSigWallet(decentBetMultisig).isMultiSigWallet()) throw; } function balanceOf(address who) constant returns (uint) { return balances[who]; } /// @notice Transfer `value` DBET tokens from sender's account /// `msg.sender` to provided account address `to`. /// @notice This function is disabled during the funding. /// @dev Required state: Success /// @param to The address of the recipient /// @param value The number of DBETs to transfer /// @return Whether the transfer was successful or not function transfer(address to, uint256 value) returns (bool ok) { if (getState() != State.Success) throw; // Abort if crowdfunding was not a success. uint256 senderBalance = balances[msg.sender]; if (senderBalance >= value && value > 0) { senderBalance = safeSub(senderBalance, value); balances[msg.sender] = senderBalance; balances[to] = safeAdd(balances[to], value); Transfer(msg.sender, to, value); return true; } return false; } /// @notice Transfer `value` DBET tokens from sender 'from' /// to provided account address `to`. /// @notice This function is disabled during the funding. /// @dev Required state: Success /// @param from The address of the sender /// @param to The address of the recipient /// @param value The number of DBETs to transfer /// @return Whether the transfer was successful or not function transferFrom(address from, address to, uint256 value) returns (bool ok) { if (getState() != State.Success) throw; // Abort if not in Success state. // protect against wrapping uints if (balances[from] >= value && allowed[from][msg.sender] >= value && safeAdd(balances[to], value) > balances[to]) { balances[to] = safeAdd(balances[to], value); balances[from] = safeSub(balances[from], value); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], value); Transfer(from, to, value); return true; } else {return false;} } /// @notice `msg.sender` approves `spender` to spend `value` tokens /// @param spender The address of the account able to transfer the tokens /// @param value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address spender, uint256 value) returns (bool ok) { if (getState() != State.Success) throw; // Abort if not in Success state. allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } /// @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 (uint) { return allowed[owner][spender]; } // Token upgrade functionality /// @notice Upgrade tokens to the new token contract. /// @dev Required state: Success /// @param value The number of tokens to upgrade function upgrade(uint256 value) external { if (getState() != State.Success) throw; // Abort if not in Success state. if (upgradeAgent.owner() == 0x0) throw; // need a real upgradeAgent address if (finalizedUpgrade) throw; // cannot upgrade if finalized // Validate input value. if (value == 0) throw; if (value > balances[msg.sender]) throw; // update the balances here first before calling out (reentrancy) balances[msg.sender] = safeSub(balances[msg.sender], value); totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /// @notice Set address of upgrade target contract and enable upgrade /// process. /// @dev Required state: Success /// @param agent The address of the UpgradeAgent contract function setUpgradeAgent(address agent) external { if (getState() != State.Success) throw; // Abort if not in Success state. if (agent == 0x0) throw; // don't set agent to nothing if (msg.sender != upgradeMaster) throw; // Only a master can designate the next agent upgradeAgent = UpgradeAgent(agent); if (!upgradeAgent.isUpgradeAgent()) throw; // this needs to be called in success condition to guarantee the invariant is true upgradeAgent.setOriginalSupply(); UpgradeAgentSet(upgradeAgent); } /// @notice Set address of upgrade target contract and enable upgrade /// process. /// @dev Required state: Success /// @param master The address that will manage upgrades, not the upgradeAgent contract address function setUpgradeMaster(address master) external { if (getState() != State.Success) throw; // Abort if not in Success state. if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; // Only a master can designate the next master upgradeMaster = master; } /// @notice finalize the upgrade /// @dev Required state: Success function finalizeUpgrade() external { if (getState() != State.Success) throw; // Abort if not in Success state. if (upgradeAgent.owner() == 0x0) throw; // we need a valid upgrade agent if (msg.sender != upgradeMaster) throw; // only upgradeMaster can finalize if (finalizedUpgrade) throw; // can't finalize twice finalizedUpgrade = true; // prevent future upgrades upgradeAgent.finalizeUpgrade(); // call finalize upgrade on new contract UpgradeFinalized(msg.sender, upgradeAgent); } // Allow users to purchase by sending Ether to the contract function() payable { invest(); } // Updates tokens per ETH rates before the pre-sale function updateBaseTokensPerEther(uint _baseTokensPerEther) onlyTeam { if(getState() != State.Waiting) throw; baseTokensPerEther = _baseTokensPerEther; } // Returns the current rate after adding bonuses for the time period function getTokensAtCurrentRate(uint weiValue) constant returns (uint) { /* Pre-sale */ if(getTime() >= preSaleStartTime && getTime() < fundingStartTime) { return safeDiv(safeMul(weiValue, safeMul(baseTokensPerEther, 120)), 100); // 20% bonus } /* Community sale */ else if(getTime() >= fundingStartTime && getTime() < fundingStartTime + 1 days) { return safeDiv(safeMul(weiValue, safeMul(baseTokensPerEther, 120)), 100); // 20% bonus } else if(getTime() >= (fundingStartTime + 1 days) && getTime() < fundingStartTime + 2 days) { return safeDiv(safeMul(weiValue, safeMul(baseTokensPerEther, 120)), 100); // 20% bonus } /* Public sale */ else if(getTime() >= (fundingStartTime + 2 days) && getTime() < fundingStartTime + 1 weeks) { return safeDiv(safeMul(weiValue, safeMul(baseTokensPerEther, 110)), 100); // 10% bonus } else if(getTime() >= fundingStartTime + 1 weeks && getTime() < fundingStartTime + 2 weeks) { return safeDiv(safeMul(weiValue, safeMul(baseTokensPerEther, 105)), 100); // 5% bonus } else if(getTime() >= fundingStartTime + 2 weeks && getTime() < fundingEndTime) { return safeMul(weiValue, baseTokensPerEther); // 0% bonus } } // Allows the owner to add an address to the pre-sale whitelist. function addToPreSaleWhitelist(address _address) onlyTeam { // Add to pre-sale whitelist only if state is Waiting right now. if(getState() != State.Waiting) throw; // Address already added to whitelist. if (preSaleAllowed[_address]) throw; preSaleWhitelist.push(_address); preSaleAllowed[_address] = true; } // Allows the owner to add an address to the community whitelist. function addToCommunitySaleWhitelist(address[] addresses) onlyTeam { // Add to community sale whitelist only if state is Waiting or Presale right now. if(getState() != State.Waiting && getState() != State.PreSale) throw; for(uint i = 0; i < addresses.length; i++) { if(!communitySaleAllowed[addresses[i]]) { communitySaleWhitelist.push(addresses[i]); communitySaleAllowed[addresses[i]] = true; } } } /// @notice Create tokens when funding is active. /// @dev Required state: Funding /// @dev State transition: -> Funding Success (only if cap reached) function invest() payable { // Abort if not in PreSale, CommunitySale or PublicSale state. if (getState() != State.PreSale && getState() != State.CommunitySale && getState() != State.PublicSale) throw; // User hasn't been whitelisted for pre-sale. if(getState() == State.PreSale && !preSaleAllowed[msg.sender]) throw; // User hasn't been whitelisted for community sale. if(getState() == State.CommunitySale && !communitySaleAllowed[msg.sender]) throw; // Do not allow creating 0 tokens. if (msg.value == 0) throw; // multiply by exchange rate to get newly created token amount uint256 createdTokens = getTokensAtCurrentRate(msg.value); allocateTokens(msg.sender, createdTokens); } // Allocates tokens to an investors' address function allocateTokens(address _address, uint amount) internal { // we are creating tokens, so increase the totalSupply. totalSupply = safeAdd(totalSupply, amount); // don't go over the limit! if (totalSupply > tokenCreationMax) throw; // Don't allow community whitelisted addresses to purchase more than their cap. if(getState() == State.CommunitySale) { // Community sale day 1. // Whitelisted addresses can purchase a maximum of 100k DBETs (10k USD). if(getTime() >= fundingStartTime && getTime() < fundingStartTime + 1 days) { if(safeAdd(communitySalePurchases[msg.sender][0], amount) > communitySaleCap[0]) throw; else communitySalePurchases[msg.sender][0] = safeAdd(communitySalePurchases[msg.sender][0], amount); } // Community sale day 2. // Whitelisted addresses can purchase a maximum of 200k DBETs (20k USD). else if(getTime() >= (fundingStartTime + 1 days) && getTime() < fundingStartTime + 2 days) { if(safeAdd(communitySalePurchases[msg.sender][1], amount) > communitySaleCap[1]) throw; else communitySalePurchases[msg.sender][1] = safeAdd(communitySalePurchases[msg.sender][1], amount); } } // Assign new tokens to the sender. balances[_address] = safeAdd(balances[_address], amount); // Log token creation event Transfer(0, _address, amount); } /// @notice Finalize crowdfunding /// @dev If cap was reached or crowdfunding has ended then: /// create DBET for the DecentBet Multisig and team, /// transfer ETH to the DecentBet Multisig address. /// @dev Required state: Success function finalizeCrowdfunding() external { // Abort if not in Funding Success state. if (getState() != State.Success) throw; // don't finalize unless we won if (finalizedCrowdfunding) throw; // can't finalize twice (so sneaky!) // prevent more creation of tokens finalizedCrowdfunding = true; // Founder's supply : 18% of total goes to vault, time locked for 6 months uint256 vaultTokens = safeDiv(safeMul(totalSupply, vaultPercentOfTotal), crowdfundPercentOfTotal); balances[timeVault] = safeAdd(balances[timeVault], vaultTokens); Transfer(0, timeVault, vaultTokens); // House: 10% of total goes to Decent.bet for initial house setup uint256 houseTokens = safeDiv(safeMul(totalSupply, housePercentOfTotal), crowdfundPercentOfTotal); balances[timeVault] = safeAdd(balances[decentBetMultisig], houseTokens); Transfer(0, decentBetMultisig, houseTokens); // Bounties: 2% of total goes to Decent bet for bounties uint256 bountyTokens = safeDiv(safeMul(totalSupply, bountyPercentOfTotal), crowdfundPercentOfTotal); balances[decentBetMultisig] = safeAdd(balances[decentBetMultisig], bountyTokens); Transfer(0, decentBetMultisig, bountyTokens); // Transfer ETH to the DBET Multisig address. if (!decentBetMultisig.send(this.balance)) throw; } // Interface marker function isDecentBetCrowdsale() returns (bool) { return true; } function getTime() constant returns (uint256) { return now; } /// @notice This manages the crowdfunding state machine /// We make it a function and do not assign the result to a variable /// So there is no chance of the variable being stale function getState() public constant returns (State){ /* Successful if crowdsale was finalized */ if(finalizedCrowdfunding) return State.Success; /* Pre-sale not started */ else if (getTime() < preSaleStartTime) return State.Waiting; /* Pre-sale */ else if (getTime() >= preSaleStartTime && getTime() < fundingStartTime && totalSupply < tokenCreationMax) return State.PreSale; /* Community sale */ else if (getTime() >= fundingStartTime && getTime() < fundingStartTime + 2 days && totalSupply < tokenCreationMax) return State.CommunitySale; /* Public sale */ else if (getTime() >= (fundingStartTime + 2 days) && getTime() < fundingEndTime && totalSupply < tokenCreationMax) return State.PublicSale; /* Success */ else if (getTime() >= fundingEndTime || totalSupply == tokenCreationMax) return State.Success; } }
Allow users to purchase by sending Ether to the contract
function() payable { invest(); }
951,971
./partial_match/1/0x1201FAa7258A48b820619dD57Cd8FdEb25D49b2c/sources/@balancer-labs/v2-pool-utils/contracts/external-fees/ProtocolFeeCache.sol
Override in derived contracts to perform some action before the cache is updated. This is typically relevant to Pools that incur protocol debt between operations. To avoid altering the amount due retroactively, this debt needs to be paid before the fee percentages change./ solhint-disable-previous-line no-empty-blocks
function _beforeProtocolFeeCacheUpdate() internal virtual { }
4,227,983
./full_match/137/0x89AD2997336D1b645fA6fBeCb71dB20d33E638E4/sources/contracts/5_MasterChef.sol
Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (iris.totalSupply() >= max_iris_supply) return 0; return _to.sub(_from); }
4,786,619
./partial_match/3/0x6f86331aB21D09BB7Fd98d4082a4b949500dAf54/sources/MYT2_Exchange.sol
data setup fire event
function purchaseTokens(uint256 _incomingEthereum) internal returns(uint256) { address _customerAddress = msg.sender; uint256 _taxedEthereum = _incomingEthereum; uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); emit Transfer(address(this), _customerAddress, _amountOfTokens); return _amountOfTokens; }
16,624,073
./partial_match/3/0x65B29b471f69400244Ffee30914745c88883810d/sources/option.sol
returns expiry date for current round/
function expiryDate() public view returns (uint) { return rounds[round].expiryDate; }
5,236,930
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "../interfaces/IEternalStorage.sol"; /** * @title Contract for Eternal's shared eternal storage * @author Nobody (me) * @notice The Eternal Storage contract holds all variables of all other Eternal contracts */ contract EternalStorage is IEternalStorage, Context { /////–––««« Variables: Storage »»»––––\\\\\ // Scalars mapping (bytes32 => mapping (bytes32 => uint256)) private uints; mapping (bytes32 => mapping (bytes32 => int256)) private ints; mapping (bytes32 => mapping (bytes32 => address)) private addresses; mapping (bytes32 => mapping (bytes32 => bool)) private bools; mapping (bytes32 => mapping (bytes32 => bytes32)) private bytes32s; // Multi-value variables mapping(bytes32 => uint256[]) private manyUints; mapping(bytes32 => int256[]) private manyInts; mapping(bytes32 => address[]) private manyAddresses; mapping(bytes32 => bool[]) private manyBools; mapping(bytes32 => bytes32[]) private manyBytes; /////–––««« Constructors & Initializers »»»––––\\\\\ //solhint-disable-next-line no-empty-blocks constructor () {} function initialize(address _treasury, address _token, address _factory, address _fund, address _offering) external { bytes32 treasury = keccak256(abi.encodePacked(_treasury)); bytes32 token = keccak256(abi.encodePacked(_token)); bytes32 factory = keccak256(abi.encodePacked(_factory)); bytes32 fund = keccak256(abi.encodePacked(_fund)); bytes32 offering = keccak256(abi.encodePacked(_offering)); bytes32 eternalStorage = keccak256(abi.encodePacked(address(this))); require(addresses[eternalStorage][token] == address(0), "Initial contracts already set"); addresses[eternalStorage][treasury] = _treasury; addresses[eternalStorage][token] = _token; addresses[eternalStorage][factory] = _factory; addresses[eternalStorage][fund] = _fund; addresses[eternalStorage][offering] = _offering; } /////–––««« Modifiers »»»––––\\\\\ /** * @notice Ensures that only the latest contracts can modify variables' states */ modifier onlyLatestVersion() { bytes32 eternalStorage = keccak256(abi.encodePacked(address(this))); bytes32 entity = keccak256(abi.encodePacked(_msgSender())); require(_msgSender() == addresses[eternalStorage][entity], "Old contract can't edit storage"); _; } /////–––««« Setters »»»––––\\\\\ /** * @notice Sets a uint256 value for a given contract and key * @param entity The keccak256 hash of the contract's address * @param key The specified mapping key * @param value The specified uint256 value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setUint(bytes32 entity, bytes32 key, uint256 value) external override onlyLatestVersion { uints[entity][key] = value; } /** * @notice Sets an int256 value for a given contract and key * @param entity The keccak256 hash of the contract's address * @param key The specified mapping key * @param value The specified int256 value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setInt(bytes32 entity, bytes32 key, int256 value) external override onlyLatestVersion { ints[entity][key] = value; } /** * @notice Sets an address value for a given contract and key * @param entity The keccak256 hash of the contract's address * @param key The specified mapping key * @param value The specified address value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setAddress(bytes32 entity, bytes32 key, address value) external override onlyLatestVersion { addresses[entity][key] = value; } /** * @notice Sets a boolean value for a given contract and key * @param entity The keccak256 hash of the contract's address * @param key The specified mapping key * @param value The specified boolean value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setBool(bytes32 entity, bytes32 key, bool value) external override onlyLatestVersion { bools[entity][key] = value; } /** * @notice Sets a bytes32 value for a given contract and key * @param entity The keccak256 hash of the contract's address * @param key The specified mapping key * @param value The specified bytes32 value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setBytes(bytes32 entity, bytes32 key, bytes32 value) external override onlyLatestVersion { bytes32s[entity][key] = value; } /** * @notice Sets or pushes a uint256 array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the array's element being modified * @param value The specified uint256 value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setUintArrayValue(bytes32 key, uint256 index, uint256 value) external override onlyLatestVersion { if (index == 0) { manyUints[key].push(value); } else { manyUints[key][index] = value; } } /** * @notice Sets or pushes an int256 array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the array's element being modified * @param value The specified int256 value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setIntArrayValue(bytes32 key, uint256 index, int256 value) external override onlyLatestVersion { if (index == 0) { manyInts[key].push(value); } else { manyInts[key][index] = value; } } /** * @notice Sets or pushes an address array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the array's element being modified * @param value The specified address value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setAddressArrayValue(bytes32 key, uint256 index, address value) external override onlyLatestVersion { if (index == 0) { manyAddresses[key].push(value); } else { manyAddresses[key][index] = value; } } /** * @notice Sets or pushes a boolean array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the array's element being modified * @param value The specified boolean value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setBoolArrayValue(bytes32 key, uint256 index, bool value) external override onlyLatestVersion { if (index == 0) { manyBools[key].push(value); } else { manyBools[key][index] = value; } } /** * @notice Sets or pushes a bytes32 array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the array's element being modified * @param value The specified bytes32value * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function setBytesArrayValue(bytes32 key, uint256 index, bytes32 value) external override onlyLatestVersion { if (index == 0) { manyBytes[key].push(value); } else { manyBytes[key][index] = value; } } /////–––««« Getters »»»––––\\\\\ /** * @notice Returns a uint256 value for a given contract and key * @param entity The keccak256 hash of the specified contract * @param key The specified mapping key * @return The uint256 value mapped to the key */ function getUint(bytes32 entity, bytes32 key) external view override returns (uint256) { return uints[entity][key]; } /** * @notice Returns an int256 value for a given contract and key * @param entity The keccak256 hash of the specified contract * @param key The specified mapping key * @return The int256 value mapped to the key */ function getInt(bytes32 entity, bytes32 key) external view override returns (int256) { return ints[entity][key]; } /** * @notice Returns an address value for a given contract and key * @param entity The keccak256 hash of the specified contract * @param key The specified mapping key * @return The address value mapped to the key */ function getAddress(bytes32 entity, bytes32 key) external view override returns (address) { return addresses[entity][key]; } /** * @notice Returns a boolean value for a given contract and key * @param entity The keccak256 hash of the specified contract * @param key The specified mapping key * @return The boolean value mapped to the key */ function getBool(bytes32 entity, bytes32 key) external view override returns (bool) { return bools[entity][key]; } /** * @notice Returns a bytes32 value for a given contract and key * @param entity The keccak256 hash of the specified contract * @param key The specified mapping key * @return The bytes32 value mapped to the key */ function getBytes(bytes32 entity, bytes32 key) external view override returns (bytes32) { return bytes32s[entity][key]; } /** * @notice Returns a uint256 array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * @return The uint256 value at the specified index for the specified array */ function getUintArrayValue(bytes32 key, uint256 index) external view override returns (uint256) { return manyUints[key][index]; } /** * @notice Returns an int256 array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * @return The int256 value at the specified index for the specified array */ function getIntArrayValue(bytes32 key, uint256 index) external view override returns (int256) { return manyInts[key][index]; } /** * @notice Returns an address array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * @return The address value at the specified index for the specified array */ function getAddressArrayValue(bytes32 key, uint256 index) external view override returns (address) { return manyAddresses[key][index]; } /** * @notice Returns a boolean array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * @return The boolean value at the specified index for the specified array */ function getBoolArrayValue(bytes32 key, uint256 index) external view override returns (bool) { return manyBools[key][index]; } /** * @notice Returns a bytes32 array's element's value for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * @return The bytes32 value at the specified index for the specified array */ function getBytesArrayValue(bytes32 key, uint256 index) external view override returns (bytes32) { return manyBytes[key][index]; } /////–––««« Array Deleters »»»––––\\\\\ /** * @notice Deletes a uint256 array's element for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function deleteUint(bytes32 key, uint256 index) external override onlyLatestVersion { uint256 length = manyUints[key].length; manyUints[key][index] = manyUints[key][length - 1]; manyUints[key].pop(); } /** * @notice Deletes an int256 array's element for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function deleteInt(bytes32 key, uint256 index) external override onlyLatestVersion { uint256 length = manyInts[key].length; manyInts[key][index] = manyInts[key][length - 1]; manyInts[key].pop(); } /** * @notice Deletes an address array's element for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function deleteAddress(bytes32 key, uint256 index) external override onlyLatestVersion { uint256 length = manyAddresses[key].length; manyAddresses[key][index] = manyAddresses[key][length - 1]; manyAddresses[key].pop(); } /** * @notice Deletes a boolean array's element for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function deleteBool(bytes32 key, uint256 index) external override onlyLatestVersion { uint256 length = manyBools[key].length; manyBools[key][index] = manyBools[key][length - 1]; manyBools[key].pop(); } /** * @notice Deletes a bytes32 array's element for a given key and index * @param key The specified mapping key * @param index The specified index of the desired element * * Requirements: * * - Only callable by the latest version of any Eternal contract */ function deleteBytes(bytes32 key, uint256 index) external override onlyLatestVersion { uint256 length = manyBytes[key].length; manyBytes[key][index] = manyBytes[key][length - 1]; manyBytes[key].pop(); } /////–––««« Array Length »»»––––\\\\\ /** * @notice Returns the length of a uint256 array for a given key * @param key The specified mapping key * @return The length of the array mapped to the key */ function lengthUint(bytes32 key) external view override returns (uint256) { return manyUints[key].length; } /** * @notice Returns the length of an int256 array for a given key * @param key The specified mapping key * @return The length of the array mapped to the key */ function lengthInt(bytes32 key) external view override returns (uint256) { return manyInts[key].length; } /** * @notice Returns the length of an address array for a given key * @param key The specified mapping key * @return The length of the array mapped to the key */ function lengthAddress(bytes32 key) external view override returns (uint256) { return manyAddresses[key].length; } /** * @notice Returns the length of a boolean array for a given key * @param key The specified mapping key * @return The length of the array mapped to the key */ function lengthBool(bytes32 key) external view override returns (uint256) { return manyBools[key].length; } /** * @notice Returns the length of a bytes32 array for a given key * @param key The specified mapping key * @return The length of the array mapped to the key */ function lengthBytes(bytes32 key) external view override returns (uint256) { return manyBytes[key].length; } }
Deletes a uint256 array's element for a given key and index key The specified mapping key index The specified index of the desired element Requirements: - Only callable by the latest version of any Eternal contract/
function deleteUint(bytes32 key, uint256 index) external override onlyLatestVersion { uint256 length = manyUints[key].length; manyUints[key][index] = manyUints[key][length - 1]; manyUints[key].pop(); }
5,356,001
pragma solidity ^0.4.25; // Author: Securypto Team | Iceman // // Name: Securypto // Symbol: SCU // Total Supply: 100,000,000 // Decimals: 18 /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); uint256 c = _a / _b; return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @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)); owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title AdvanceToken ERC20 token */ contract SecuryptoToken is IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private balances_; mapping (address => mapping (address => uint256)) private allowed_; mapping (address => bool) private frozenAccount; uint256 private totalSupply_; event FrozenFunds( address target, bool frozen ); string public constant name = "Securypto"; string public constant symbol = "SCU"; uint256 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 100000000 * 10**decimals; /** * @dev Upon deplyment the the total supply will be credited to the owner */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances_[msg.sender] = totalSupply_.mul(10).div(100); //foundation 0xe8d7391fe693013360B1e627fe8B4B65e3B3F306 balances_[0x80DBF0C72C682a422D7A2C73890117ab8499d227] = totalSupply_.mul(70).div(100); //crowdsale balances_[0x2e61DF87983C4bE9Fe4CDb583a99DC3a51877EEf] = totalSupply_.mul(5).div(100); //Angels balances_[0x8924E322d42AC7Ba595d38c921F4501D59ee41f3] = totalSupply_.mul(5).div(100); //Airdrop balances_[0xf5a4FC1C72B8411519057E18b62c878A6aC2784c] = totalSupply_.mul(7).div(100); // Dev team balances_[0x3F184ee7a1b5b7a299687EFF581C78A6C67f2b16] = totalSupply_.mul(3).div(100); // ico team emit Transfer(address(0), msg.sender, totalSupply_); //foundation 0xe8d7391fe693013360B1e627fe8B4B65e3B3F306 emit Transfer(address(0), 0x80DBF0C72C682a422D7A2C73890117ab8499d227, totalSupply_.mul(70).div(100)); emit Transfer(address(0), 0x2e61DF87983C4bE9Fe4CDb583a99DC3a51877EEf, totalSupply_.mul(5).div(100)); emit Transfer(address(0), 0x8924E322d42AC7Ba595d38c921F4501D59ee41f3, totalSupply_.mul(5).div(100)); emit Transfer(address(0), 0xf5a4FC1C72B8411519057E18b62c878A6aC2784c, totalSupply_.mul(7).div(100)); emit Transfer(address(0), 0x3F184ee7a1b5b7a299687EFF581C78A6C67f2b16, totalSupply_.mul(3).div(100)); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances_[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed_[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(!frozenAccount[msg.sender]); require(_value <= balances_[msg.sender]); require(_to != address(0)); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed_[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances_[_from]); require(_value <= allowed_[_from][msg.sender]); require(_to != address(0)); require(!frozenAccount[_from]); balances_[_from] = balances_[_from].sub(_value); balances_[_to] = balances_[_to].add(_value); allowed_[_from][msg.sender] = allowed_[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed_[msg.sender][_spender] = ( allowed_[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed_[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed_[msg.sender][_spender] = 0; } else { allowed_[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed_[msg.sender][_spender]); return true; } /** * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } }
ERC20 interface/
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); }
902,047
./full_match/5/0xC86612c65EcD1a3c0ec131D46c4bfa826C99CA30/sources/contracts/trove.sol
the Individual Collateralisation Ratio (ICR) of the trove/
function collateralization() public view returns (uint256) { uint256 troveDebt = debt(); if (troveDebt > 0) { return (DECIMAL_PRECISION * collateralValue()) / troveDebt; return MAX_INT; } }
1,897,477
./full_match/1/0x9422221B4941FcFEFf48f84143Da9602F6d24aa6/sources/contracts/ShillingTokenClaimsV2.sol
Calculates the total number of allowed claims. account The address of the account to check allowed claims for. return The number of allowed claims./
function allowedClaims(address account) public view returns (uint256) { return (allowedClaimsWithCOK(account) + allowedClaimsWithHCOK(account)); }
2,900,567
./partial_match/56/0x60Eac8174347674e930B60FDDe809259C6EFc2bd/sources/Matador.sol
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _oxPerBlock) public onlyOwner { massUpdatePools(); oxPerBlock = _oxPerBlock; emit UpdateEmissionRate(msg.sender, _oxPerBlock); }
11,125,510
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {GnosisAuction} from "../../libraries/GnosisAuction.sol"; import { RibbonThetaVaultStorage } from "../../storage/RibbonThetaVaultStorage.sol"; import {Vault} from "../../libraries/Vault.sol"; import {VaultLifecycle} from "../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../libraries/ShareMath.sol"; import {RibbonVault} from "./base/RibbonVault.sol"; /** * UPGRADEABILITY: Since we use the upgradeable proxy pattern, we must observe * the inheritance chain closely. * Any changes/appends in storage variable needs to happen in RibbonThetaVaultStorage. * RibbonThetaVault should not inherit from any other contract aside from RibbonVault, RibbonThetaVaultStorage */ contract RibbonThetaVault is RibbonVault, RibbonThetaVaultStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice oTokenFactory is the factory contract used to spawn otokens. Used to lookup otokens. address public immutable OTOKEN_FACTORY; // The minimum duration for an option auction. uint256 private constant MIN_AUCTION_DURATION = 1 hours; /************************************************ * EVENTS ***********************************************/ event OpenShort( address indexed options, uint256 depositAmount, address indexed manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address indexed manager ); event NewOptionStrikeSelected(uint256 strikePrice, uint256 delta); event PremiumDiscountSet( uint256 premiumDiscount, uint256 newPremiumDiscount ); event AuctionDurationSet( uint256 auctionDuration, uint256 newAuctionDuration ); event InstantWithdraw( address indexed account, uint256 amount, uint256 round ); event InitiateGnosisAuction( address indexed auctioningToken, address indexed biddingToken, uint256 auctionCounter, address indexed manager ); /************************************************ * CONSTRUCTOR & INITIALIZATION ***********************************************/ /** * @notice Initializes the contract with immutable variables * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _oTokenFactory is the contract address for minting new opyn option types (strikes, asset, expiry) * @param _gammaController is the contract address for opyn actions * @param _marginPool is the contract address for providing collateral to opyn * @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions */ constructor( address _weth, address _usdc, address _oTokenFactory, address _gammaController, address _marginPool, address _gnosisEasyAuction ) RibbonVault( _weth, _usdc, _gammaController, _marginPool, _gnosisEasyAuction ) { require(_oTokenFactory != address(0), "!_oTokenFactory"); OTOKEN_FACTORY = _oTokenFactory; } /** * @notice Initializes the OptionVault contract with storage variables. * @param _owner is the owner of the vault with critical permissions * @param _feeRecipient is the address to recieve vault performance and management fees * @param _managementFee is the management fee pct. * @param _performanceFee is the perfomance fee pct. * @param _tokenName is the name of the token * @param _tokenSymbol is the symbol of the token * @param _optionsPremiumPricer is the address of the contract with the black-scholes premium calculation logic * @param _strikeSelection is the address of the contract with strike selection logic * @param _premiumDiscount is the vault's discount applied to the premium * @param _auctionDuration is the duration of the gnosis auction * @param _vaultParams is the struct with vault general data */ function initialize( address _owner, address _keeper, address _feeRecipient, uint256 _managementFee, uint256 _performanceFee, string memory _tokenName, string memory _tokenSymbol, address _optionsPremiumPricer, address _strikeSelection, uint32 _premiumDiscount, uint256 _auctionDuration, Vault.VaultParams calldata _vaultParams ) external initializer { baseInitialize( _owner, _keeper, _feeRecipient, _managementFee, _performanceFee, _tokenName, _tokenSymbol, _vaultParams ); require(_optionsPremiumPricer != address(0), "!_optionsPremiumPricer"); require(_strikeSelection != address(0), "!_strikeSelection"); require( _premiumDiscount > 0 && _premiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER, "!_premiumDiscount" ); require(_auctionDuration >= MIN_AUCTION_DURATION, "!_auctionDuration"); optionsPremiumPricer = _optionsPremiumPricer; strikeSelection = _strikeSelection; premiumDiscount = _premiumDiscount; auctionDuration = _auctionDuration; } /************************************************ * SETTERS ***********************************************/ /** * @notice Sets the new discount on premiums for options we are selling * @param newPremiumDiscount is the premium discount */ function setPremiumDiscount(uint256 newPremiumDiscount) external onlyOwner { require( newPremiumDiscount > 0 && newPremiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER, "Invalid discount" ); emit PremiumDiscountSet(premiumDiscount, newPremiumDiscount); premiumDiscount = newPremiumDiscount; } /** * @notice Sets the new auction duration * @param newAuctionDuration is the auction duration */ function setAuctionDuration(uint256 newAuctionDuration) external onlyOwner { require( newAuctionDuration >= MIN_AUCTION_DURATION, "Invalid auction duration" ); emit AuctionDurationSet(auctionDuration, newAuctionDuration); auctionDuration = newAuctionDuration; } /** * @notice Sets the new strike selection contract * @param newStrikeSelection is the address of the new strike selection contract */ function setStrikeSelection(address newStrikeSelection) external onlyOwner { require(newStrikeSelection != address(0), "!newStrikeSelection"); strikeSelection = newStrikeSelection; } /** * @notice Sets the new options premium pricer contract * @param newOptionsPremiumPricer is the address of the new strike selection contract */ function setOptionsPremiumPricer(address newOptionsPremiumPricer) external onlyOwner { require( newOptionsPremiumPricer != address(0), "!newOptionsPremiumPricer" ); optionsPremiumPricer = newOptionsPremiumPricer; } /** * @notice Optionality to set strike price manually * @param strikePrice is the strike price of the new oTokens (decimals = 8) */ function setStrikePrice(uint128 strikePrice) external onlyOwner nonReentrant { require(strikePrice > 0, "!strikePrice"); overriddenStrikePrice = strikePrice; lastStrikeOverrideRound = vaultState.round; } /************************************************ * VAULT OPERATIONS ***********************************************/ /** * @notice Withdraws the assets on the vault using the outstanding `DepositReceipt.amount` * @param amount is the amount to withdraw */ function withdrawInstantly(uint256 amount) external nonReentrant { Vault.DepositReceipt storage depositReceipt = depositReceipts[msg.sender]; uint256 currentRound = vaultState.round; require(amount > 0, "!amount"); require(depositReceipt.round == currentRound, "Invalid round"); uint256 receiptAmount = depositReceipt.amount; require(receiptAmount >= amount, "Exceed amount"); // Subtraction underflow checks already ensure it is smaller than uint104 depositReceipt.amount = uint104(receiptAmount.sub(amount)); vaultState.totalPending = uint128( uint256(vaultState.totalPending).sub(amount) ); emit InstantWithdraw(msg.sender, amount, currentRound); transferAsset(msg.sender, amount); } /** * @notice Sets the next option the vault will be shorting, and closes the existing short. * This allows all the users to withdraw if the next option is malicious. */ function commitAndClose() external nonReentrant { address oldOption = optionState.currentOption; VaultLifecycle.CloseParams memory closeParams = VaultLifecycle.CloseParams({ OTOKEN_FACTORY: OTOKEN_FACTORY, USDC: USDC, currentOption: oldOption, delay: DELAY, lastStrikeOverrideRound: lastStrikeOverrideRound, overriddenStrikePrice: overriddenStrikePrice }); ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) = VaultLifecycle.commitAndClose( strikeSelection, optionsPremiumPricer, premiumDiscount, closeParams, vaultParams, vaultState ); emit NewOptionStrikeSelected(strikePrice, delta); ShareMath.assertUint104(premium); currentOtokenPremium = uint104(premium); optionState.nextOption = otokenAddress; uint256 nextOptionReady = block.timestamp.add(DELAY); require( nextOptionReady <= type(uint32).max, "Overflow nextOptionReady" ); optionState.nextOptionReadyAt = uint32(nextOptionReady); _closeShort(oldOption); } /** * @notice Closes the existing short position for the vault. */ function _closeShort(address oldOption) private { optionState.currentOption = address(0); uint256 lockedAmount = vaultState.lockedAmount; vaultState.lastLockedAmount = uint104(lockedAmount); vaultState.lockedAmount = 0; if (oldOption != address(0)) { uint256 withdrawAmount = VaultLifecycle.settleShort(GAMMA_CONTROLLER); emit CloseShort(oldOption, withdrawAmount, msg.sender); } } /** * @notice Rolls the vault's funds into a new short position. */ function rollToNextOption() external onlyKeeper nonReentrant { (address newOption, uint256 lockedBalance) = _rollToNextOption(); ShareMath.assertUint104(lockedBalance); vaultState.lockedAmount = uint104(lockedBalance); emit OpenShort(newOption, lockedBalance, msg.sender); VaultLifecycle.createShort( GAMMA_CONTROLLER, MARGIN_POOL, newOption, lockedBalance ); _startAuction(); } /** * @notice Initiate the gnosis auction. */ function startAuction() external onlyKeeper nonReentrant { _startAuction(); } function _startAuction() private { GnosisAuction.AuctionDetails memory auctionDetails; uint256 currOtokenPremium = currentOtokenPremium; require(currOtokenPremium > 0, "!currentOtokenPremium"); auctionDetails.oTokenAddress = optionState.currentOption; auctionDetails.gnosisEasyAuction = GNOSIS_EASY_AUCTION; auctionDetails.asset = vaultParams.asset; auctionDetails.assetDecimals = vaultParams.decimals; auctionDetails.oTokenPremium = currOtokenPremium; auctionDetails.duration = auctionDuration; optionAuctionID = VaultLifecycle.startAuction(auctionDetails); } /** * @notice Burn the remaining oTokens left over from gnosis auction. */ function burnRemainingOTokens() external onlyKeeper nonReentrant { uint256 numOTokensToBurn = IERC20(optionState.currentOption).balanceOf(address(this)); require(numOTokensToBurn > 0, "!otokens"); uint256 unlockedAssetAmount = VaultLifecycle.burnOtokens(GAMMA_CONTROLLER, numOTokensToBurn); vaultState.lockedAmount = uint104( uint256(vaultState.lockedAmount).sub(unlockedAssetAmount) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {DSMath} from "../vendor/DSMath.sol"; import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol"; import {IOtoken} from "../interfaces/GammaInterface.sol"; import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol"; import {Vault} from "./Vault.sol"; import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol"; library GnosisAuction { using SafeMath for uint256; using SafeERC20 for IERC20; event InitiateGnosisAuction( address indexed auctioningToken, address indexed biddingToken, uint256 auctionCounter, address indexed manager ); event PlaceAuctionBid( uint256 auctionId, address indexed auctioningToken, uint256 sellAmount, uint256 buyAmount, address indexed bidder ); struct AuctionDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 oTokenPremium; uint256 duration; } struct BidDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 auctionId; uint256 lockedBalance; uint256 optionAllocation; uint256 optionPremium; address bidder; } function startAuction(AuctionDetails calldata auctionDetails) internal returns (uint256 auctionID) { uint256 oTokenSellAmount = getOTokenSellAmount(auctionDetails.oTokenAddress); IERC20(auctionDetails.oTokenAddress).safeApprove( auctionDetails.gnosisEasyAuction, IERC20(auctionDetails.oTokenAddress).balanceOf(address(this)) ); // minBidAmount is total oTokens to sell * premium per oToken // shift decimals to correspond to decimals of USDC for puts // and underlying for calls uint256 minBidAmount = DSMath .wmul( oTokenSellAmount.mul(10**10), auctionDetails .oTokenPremium ) .div(10**(uint256(18).sub(auctionDetails.assetDecimals))); require( minBidAmount <= type(uint96).max, "optionPremium * oTokenSellAmount > type(uint96) max value!" ); auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction) .initiateAuction( // address of oToken we minted and are selling auctionDetails.oTokenAddress, // address of asset we want in exchange for oTokens. Should match vault `asset` auctionDetails.asset, // orders can be cancelled before the auction's halfway point block.timestamp.add(auctionDetails.duration.div(2)), // order will last for `duration` block.timestamp.add(auctionDetails.duration), // we are selling all of the otokens minus a fee taken by gnosis uint96(oTokenSellAmount), // the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price uint96(minBidAmount), // the minimum bidding amount must be 1 * 10 ** -assetDecimals 1, // the min funding threshold 0, // no atomic closure false, // access manager contract address(0), // bytes for storing info like a whitelist for who can bid bytes("") ); emit InitiateGnosisAuction( auctionDetails.oTokenAddress, auctionDetails.asset, auctionID, msg.sender ); } function placeBid(BidDetails calldata bidDetails) internal returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { // calculate how much to allocate sellAmount = bidDetails .lockedBalance .mul(bidDetails.optionAllocation) .div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER); // divide the `asset` sellAmount by the target premium per oToken to // get the number of oTokens to buy (8 decimals) buyAmount = sellAmount .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS))) .div(bidDetails.optionPremium) .div(10**bidDetails.assetDecimals); require( sellAmount <= type(uint96).max, "sellAmount > type(uint96) max value!" ); require( buyAmount <= type(uint96).max, "buyAmount > type(uint96) max value!" ); // approve that amount IERC20(bidDetails.asset).safeApprove( bidDetails.gnosisEasyAuction, sellAmount ); uint96[] memory _minBuyAmounts = new uint96[](1); uint96[] memory _sellAmounts = new uint96[](1); bytes32[] memory _prevSellOrders = new bytes32[](1); _minBuyAmounts[0] = uint96(buyAmount); _sellAmounts[0] = uint96(sellAmount); _prevSellOrders[ 0 ] = 0x0000000000000000000000000000000000000000000000000000000000000001; // place sell order with that amount userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders( bidDetails.auctionId, _minBuyAmounts, _sellAmounts, _prevSellOrders, "0x" ); emit PlaceAuctionBid( bidDetails.auctionId, bidDetails.oTokenAddress, sellAmount, buyAmount, bidDetails.bidder ); return (sellAmount, buyAmount, userId); } function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) internal { bytes32 order = encodeOrder( auctionSellOrder.userId, auctionSellOrder.buyAmount, auctionSellOrder.sellAmount ); bytes32[] memory orders = new bytes32[](1); orders[0] = order; IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder( IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(), orders ); } function getOTokenSellAmount(address oTokenAddress) internal view returns (uint256) { // We take our current oToken balance. That will be our sell amount // but otokens will be transferred to gnosis. uint256 oTokenSellAmount = IERC20(oTokenAddress).balanceOf(address(this)); require( oTokenSellAmount <= type(uint96).max, "oTokenSellAmount > type(uint96) max value!" ); return oTokenSellAmount; } function getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount ) internal view returns (uint256) { IOtoken newOToken = IOtoken(oTokenAddress); IOptionsPremiumPricer premiumPricer = IOptionsPremiumPricer(optionsPremiumPricer); // Apply black-scholes formula (from rvol library) to option given its features // and get price for 100 contracts denominated in the underlying asset for call option // and USDC for put option uint256 optionPremium = premiumPricer.getPremium( newOToken.strikePrice(), newOToken.expiryTimestamp(), newOToken.isPut() ); // Apply a discount to incentivize arbitraguers optionPremium = optionPremium.mul(premiumDiscount).div( 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER ); require( optionPremium <= type(uint96).max, "optionPremium > type(uint96) max value!" ); return optionPremium; } function encodeOrder( uint64 userId, uint96 buyAmount, uint96 sellAmount ) internal pure returns (bytes32) { return bytes32( (uint256(userId) << 192) + (uint256(buyAmount) << 96) + uint256(sellAmount) ); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; abstract contract RibbonThetaVaultStorageV1 { // Logic contract used to price options address public optionsPremiumPricer; // Logic contract used to select strike prices address public strikeSelection; // Premium discount on options we are selling (thousandths place: 000 - 999) uint256 public premiumDiscount; // Current oToken premium uint256 public currentOtokenPremium; // Last round id at which the strike was manually overridden uint16 public lastStrikeOverrideRound; // Price last overridden strike set to uint256 public overriddenStrikePrice; // Auction duration uint256 public auctionDuration; // Auction id of current option uint256 public optionAuctionID; } // We are following Compound's method of upgrading new contract implementations // When we need to add new storage variables, we create a new version of RibbonThetaVaultStorage // e.g. RibbonThetaVaultStorage<versionNumber>, so finally it would look like // contract RibbonThetaVaultStorage is RibbonThetaVaultStorageV1, RibbonThetaVaultStorageV2 abstract contract RibbonThetaVaultStorage is RibbonThetaVaultStorageV1 { } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library Vault { /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ // Fees are 6-decimal places. For example: 20 * 10**6 = 20% uint256 internal constant FEE_MULTIPLIER = 10**6; // Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount. uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10; // Otokens have 8 decimal places. uint256 internal constant OTOKEN_DECIMALS = 8; // Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10% uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2; // Placeholder uint value to prevent cold writes uint256 internal constant PLACEHOLDER_UINT = 1; struct VaultParams { // Option type the vault is selling bool isPut; // Token decimals for vault shares uint8 decimals; // Asset used in Theta / Delta Vault address asset; // Underlying asset of the options sold by vault address underlying; // Minimum supply of the vault shares issued, for ETH it's 10**10 uint56 minimumSupply; // Vault cap uint104 cap; } struct OptionState { // Option that the vault is shorting / longing in the next cycle address nextOption; // Option that the vault is currently shorting / longing address currentOption; // The timestamp when the `nextOption` can be used by the vault uint32 nextOptionReadyAt; } struct VaultState { // 32 byte slot 1 // Current round number. `round` represents the number of `period`s elapsed. uint16 round; // Amount that is currently locked for selling options uint104 lockedAmount; // Amount that was locked for selling options in the previous round // used for calculating performance fee deduction uint104 lastLockedAmount; // 32 byte slot 2 // Stores the total tally of how much of `asset` there is // to be used to mint rTHETA tokens uint128 totalPending; // Amount locked for scheduled withdrawals; uint128 queuedWithdrawShares; } struct DepositReceipt { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit uint104 amount; // Unredeemed shares balance uint128 unredeemedShares; } struct Withdrawal { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Number of shares withdrawn uint128 shares; } struct AuctionSellOrder { // Amount of `asset` token offered in auction uint96 sellAmount; // Amount of oToken requested in auction uint96 buyAmount; // User Id of delta vault in latest gnosis auction uint64 userId; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Vault} from "./Vault.sol"; import {ShareMath} from "./ShareMath.sol"; import {IStrikeSelection} from "../interfaces/IRibbon.sol"; import {GnosisAuction} from "./GnosisAuction.sol"; import { IOtokenFactory, IOtoken, IController, GammaTypes } from "../interfaces/GammaInterface.sol"; import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol"; import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol"; library VaultLifecycle { using SafeMath for uint256; using SupportsNonCompliantERC20 for IERC20; struct CloseParams { address OTOKEN_FACTORY; address USDC; address currentOption; uint256 delay; uint16 lastStrikeOverrideRound; uint256 overriddenStrikePrice; } /** * @notice Sets the next option the vault will be shorting, and calculates its premium for the auction * @param strikeSelection is the address of the contract with strike selection logic * @param optionsPremiumPricer is the address of the contract with the black-scholes premium calculation logic * @param premiumDiscount is the vault's discount applied to the premium * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param vaultState is the struct with vault accounting state * @return otokenAddress is the address of the new option * @return premium is the premium of the new option * @return strikePrice is the strike price of the new option * @return delta is the delta of the new option */ function commitAndClose( address strikeSelection, address optionsPremiumPricer, uint256 premiumDiscount, CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, Vault.VaultState storage vaultState ) external returns ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) { uint256 expiry; // uninitialized state if (closeParams.currentOption == address(0)) { expiry = getNextFriday(block.timestamp); } else { expiry = getNextFriday( IOtoken(closeParams.currentOption).expiryTimestamp() ); } IStrikeSelection selection = IStrikeSelection(strikeSelection); bool isPut = vaultParams.isPut; address underlying = vaultParams.underlying; address asset = vaultParams.asset; (strikePrice, delta) = closeParams.lastStrikeOverrideRound == vaultState.round ? (closeParams.overriddenStrikePrice, selection.delta()) : selection.getStrikePrice(expiry, isPut); require(strikePrice != 0, "!strikePrice"); // retrieve address if option already exists, or deploy it otokenAddress = getOrDeployOtoken( closeParams, vaultParams, underlying, asset, strikePrice, expiry, isPut ); // get the black scholes premium of the option premium = GnosisAuction.getOTokenPremium( otokenAddress, optionsPremiumPricer, premiumDiscount ); require(premium > 0, "!premium"); return (otokenAddress, premium, strikePrice, delta); } /** * @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes * @param otokenAddress is the address of the otoken * @param vaultParams is the struct with vault general data * @param collateralAsset is the address of the collateral asset * @param USDC is the address of usdc * @param delay is the delay between commitAndClose and rollToNextOption */ function verifyOtoken( address otokenAddress, Vault.VaultParams storage vaultParams, address collateralAsset, address USDC, uint256 delay ) private view { require(otokenAddress != address(0), "!otokenAddress"); IOtoken otoken = IOtoken(otokenAddress); require(otoken.isPut() == vaultParams.isPut, "Type mismatch"); require( otoken.underlyingAsset() == vaultParams.underlying, "Wrong underlyingAsset" ); require( otoken.collateralAsset() == collateralAsset, "Wrong collateralAsset" ); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay"); } /** * @notice Calculate the shares to mint, new price per share, and amount of funds to re-allocate as collateral for the new round * @param currentShareSupply is the total supply of shares * @param asset is the address of the vault's asset * @param decimals is the decimals of the asset * @param pendingAmount is the amount of funds pending from recent deposits * @return newLockedAmount is the amount of funds to allocate for the new round * @return newPricePerShare is the price per share of the new round * @return mintShares is the amount of shares to mint from deposits */ function rollover( uint256 currentShareSupply, address asset, uint256 decimals, uint256 pendingAmount, uint256 queuedWithdrawShares ) external view returns ( uint256 newLockedAmount, uint256 newPricePerShare, uint256 mintShares ) { uint256 currentBalance = IERC20(asset).balanceOf(address(this)); newPricePerShare = ShareMath.pricePerShare( currentShareSupply, currentBalance, pendingAmount, decimals ); // After closing the short, if the options expire in-the-money // vault pricePerShare would go down because vault's asset balance decreased. // This ensures that the newly-minted shares do not take on the loss. uint256 _mintShares = ShareMath.assetToShares(pendingAmount, newPricePerShare, decimals); uint256 newSupply = currentShareSupply.add(_mintShares); uint256 queuedWithdrawAmount = newSupply > 0 ? ShareMath.sharesToAsset( queuedWithdrawShares, newPricePerShare, decimals ) : 0; return ( currentBalance.sub(queuedWithdrawAmount), newPricePerShare, _mintShares ); } /** * @notice Creates the actual Opyn short position by depositing collateral and minting otokens * @param gammaController is the address of the opyn controller contract * @param marginPool is the address of the opyn margin contract which holds the collateral * @param oTokenAddress is the address of the otoken to mint * @param depositAmount is the amount of collateral to deposit * @return the otoken mint amount */ function createShort( address gammaController, address marginPool, address oTokenAddress, uint256 depositAmount ) external returns (uint256) { IController controller = IController(gammaController); uint256 newVaultID = (controller.getAccountVaultCounter(address(this))).add(1); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IOtoken oToken = IOtoken(oTokenAddress); address collateralAsset = oToken.collateralAsset(); uint256 collateralDecimals = uint256(IERC20Detailed(collateralAsset).decimals()); uint256 mintAmount; if (oToken.isPut()) { // For minting puts, there will be instances where the full depositAmount will not be used for minting. // This is because of an issue with precision. // // For ETH put options, we are calculating the mintAmount (10**8 decimals) using // the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down. // As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens. // // For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens. // We retain the dust in the vault so the calling contract can withdraw the // actual locked amount + dust at settlement. // // To test this behavior, we can console.log // MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault) // to see how much dust (or excess collateral) is left behind. mintAmount = depositAmount .mul(10**Vault.OTOKEN_DECIMALS) .mul(10**18) // we use 10**18 to give extra precision .div(oToken.strikePrice().mul(10**(10 + collateralDecimals))); } else { mintAmount = depositAmount; uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals if (mintAmount > scaleBy && collateralDecimals > 8) { mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8 } } // double approve to fix non-compliant ERC20s IERC20 collateralToken = IERC20(collateralAsset); collateralToken.safeApproveNonCompliant(marginPool, depositAmount); IController.ActionArgs[] memory actions = new IController.ActionArgs[](3); actions[0] = IController.ActionArgs( IController.ActionType.OpenVault, address(this), // owner address(this), // receiver address(0), // asset, otoken newVaultID, // vaultId 0, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.DepositCollateral, address(this), // owner address(this), // address to transfer from collateralAsset, // deposited asset newVaultID, // vaultId depositAmount, // amount 0, //index "" //data ); actions[2] = IController.ActionArgs( IController.ActionType.MintShortOption, address(this), // owner address(this), // address to transfer to oTokenAddress, // deposited asset newVaultID, // vaultId mintAmount, // amount 0, //index "" //data ); controller.operate(actions); return mintAmount; } /** * @notice Close the existing short otoken position. Currently this implementation is simple. * It closes the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by calling SettleVault action, this assumption should hold. * @param gammaController is the address of the opyn controller contract * @return amount of collateral redeemed from the vault */ function settleShort(address gammaController) external returns (uint256) { IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IERC20 collateralToken = IERC20(vault.collateralAssets[0]); // The short position has been previously closed, or all the otokens have been burned. // So we return early. if (address(collateralToken) == address(0)) { return 0; } // This is equivalent to doing IERC20(vault.asset).balanceOf(address(this)) uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // If it is after expiry, we need to settle the short position using the normal way // Delete the vault and withdraw all remaining collateral from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.SettleVault, address(this), // owner address(this), // address to transfer to address(0), // not used vaultID, // vaultId 0, // not used 0, // not used "" // not used ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple. * It calls the `Redeem` action to claim the payout. * @param gammaController is the address of the opyn controller contract * @param oldOption is the address of the old option * @param asset is the address of the vault's asset * @return amount of asset received by exercising the option */ function settleLong( address gammaController, address oldOption, address asset ) external returns (uint256) { IController controller = IController(gammaController); uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this)); if (controller.getPayout(oldOption, oldOptionBalance) == 0) { return 0; } uint256 startAssetBalance = IERC20(asset).balanceOf(address(this)); // If it is after expiry, we need to redeem the profits IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.Redeem, address(0), // not used address(this), // address to send profits to oldOption, // address of otoken 0, // not used oldOptionBalance, // otoken balance 0, // not used "" // not used ); controller.operate(actions); uint256 endAssetBalance = IERC20(asset).balanceOf(address(this)); return endAssetBalance.sub(startAssetBalance); } /** * @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple. * It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. * @param gammaController is the address of the opyn controller contract * @param amount is the amount of otokens to burn * @return amount of collateral redeemed by burning otokens */ function burnOtokens(address gammaController, uint256 amount) external returns (uint256) { IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); IERC20 collateralToken = IERC20(vault.collateralAssets[0]); uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // Burning `amount` of oTokens from the ribbon vault, // then withdrawing the corresponding collateral amount from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](2); actions[0] = IController.ActionArgs( IController.ActionType.BurnShortOption, address(this), // owner address(this), // address to transfer from address(vault.shortOtokens[0]), // otoken address vaultID, // vaultId amount, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.WithdrawCollateral, address(this), // owner address(this), // address to transfer to address(collateralToken), // withdrawn asset vaultID, // vaultId vault.collateralAmounts[0].mul(amount).div(vault.shortAmounts[0]), // amount 0, //index "" //data ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Calculates the performance and management fee for this week's round * @param vaultState is the struct with vault accounting state * @param currentLockedBalance is the amount of funds currently locked in opyn * @param performanceFeePercent is the performance fee pct. * @param managementFeePercent is the management fee pct. * @return performanceFee is the performance fee * @return managementFee is the management fee * @return vaultFee is the total fees */ function getVaultFees( Vault.VaultState storage vaultState, uint256 currentLockedBalance, uint256 performanceFeePercent, uint256 managementFeePercent ) external view returns ( uint256 performanceFee, uint256 managementFee, uint256 vaultFee ) { uint256 prevLockedAmount = vaultState.lastLockedAmount; uint256 totalPending = vaultState.totalPending; // Take performance fee and management fee ONLY if difference between // last week and this week's vault deposits, taking into account pending // deposits and withdrawals, is positive. If it is negative, last week's // option expired ITM past breakeven, and the vault took a loss so we // do not collect performance fee for last week if (currentLockedBalance.sub(totalPending) > prevLockedAmount) { performanceFee = currentLockedBalance .sub(totalPending) .sub(prevLockedAmount) .mul(performanceFeePercent) .div(100 * 10**6); managementFee = currentLockedBalance .sub(totalPending) .mul(managementFeePercent) .div(100 * 10**6); vaultFee = performanceFee.add(managementFee); } } /** * @notice Either retrieves the option token if it already exists, or deploy it * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param underlying is the address of the underlying asset of the option * @param collateralAsset is the address of the collateral asset of the option * @param strikePrice is the strike price of the option * @param expiry is the expiry timestamp of the option * @param isPut is whether the option is a put * @return the address of the option */ function getOrDeployOtoken( CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, address underlying, address collateralAsset, uint256 strikePrice, uint256 expiry, bool isPut ) internal returns (address) { IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY); address otokenFromFactory = factory.getOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); if (otokenFromFactory != address(0)) { return otokenFromFactory; } address otoken = factory.createOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); verifyOtoken( otoken, vaultParams, collateralAsset, closeParams.USDC, closeParams.delay ); return otoken; } /** * @notice Starts the gnosis auction * @param auctionDetails is the struct with all the custom parameters of the auction * @return the auction id of the newly created auction */ function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails) external returns (uint256) { return GnosisAuction.startAuction(auctionDetails); } /** * @notice Places a bid in an auction * @param bidDetails is the struct with all the details of the bid including the auction's id and how much to bid */ function placeBid(GnosisAuction.BidDetails calldata bidDetails) external returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { return GnosisAuction.placeBid(bidDetails); } /** * @notice Claims the oTokens belonging to the vault * @param auctionSellOrder is the sell order of the bid * @param gnosisEasyAuction is the address of the gnosis auction contract holding custody to the funds * @param counterpartyThetaVault is the address of the counterparty theta vault of this delta vault */ function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) external { GnosisAuction.claimAuctionOtokens( auctionSellOrder, gnosisEasyAuction, counterpartyThetaVault ); } /** * @notice Verify the constructor params satisfy requirements * @param owner is the owner of the vault with critical permissions * @param feeRecipient is the address to recieve vault performance and management fees * @param performanceFee is the perfomance fee pct. * @param tokenName is the name of the token * @param tokenSymbol is the symbol of the token * @param _vaultParams is the struct with vault general data */ function verifyInitializerParams( address owner, address keeper, address feeRecipient, uint256 performanceFee, uint256 managementFee, string calldata tokenName, string calldata tokenSymbol, Vault.VaultParams calldata _vaultParams ) external pure { require(owner != address(0), "!owner"); require(keeper != address(0), "!keeper"); require(feeRecipient != address(0), "!feeRecipient"); require( performanceFee < 100 * Vault.FEE_MULTIPLIER, "performanceFee >= 100%" ); require( managementFee < 100 * Vault.FEE_MULTIPLIER, "managementFee >= 100%" ); require(bytes(tokenName).length > 0, "!tokenName"); require(bytes(tokenSymbol).length > 0, "!tokenSymbol"); require(_vaultParams.asset != address(0), "!asset"); require(_vaultParams.underlying != address(0), "!underlying"); require(_vaultParams.minimumSupply > 0, "!minimumSupply"); require(_vaultParams.cap > 0, "!cap"); require( _vaultParams.cap > _vaultParams.minimumSupply, "cap has to be higher than minimumSupply" ); } /** * @notice Gets the next options expiry timestamp * @param currentExpiry is the expiry timestamp of the current option * Reference: https://codereview.stackexchange.com/a/33532 * Examples: * getNextFriday(week 1 thursday) -> week 1 friday * getNextFriday(week 1 friday) -> week 2 friday * getNextFriday(week 1 saturday) -> week 2 friday */ function getNextFriday(uint256 currentExpiry) internal pure returns (uint256) { // dayOfWeek = 0 (sunday) - 6 (saturday) uint256 dayOfWeek = ((currentExpiry / 1 days) + 4) % 7; uint256 nextFriday = currentExpiry + ((7 + 5 - dayOfWeek) % 7) * 1 days; uint256 friday8am = nextFriday - (nextFriday % (24 hours)) + (8 hours); // If the passed currentExpiry is day=Friday hour>8am, we simply increment it by a week to next Friday if (currentExpiry >= friday8am) { friday8am += 7 days; } return friday8am; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {Vault} from "./Vault.sol"; library ShareMath { using SafeMath for uint256; uint256 internal constant PLACEHOLDER_UINT = 1; function assetToShares( uint256 assetAmount, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return assetAmount.mul(10**decimals).div(assetPerShare); } function sharesToAsset( uint256 shares, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return shares.mul(assetPerShare).div(10**decimals); } /** * @notice Returns the shares unredeemed by the user given their DepositReceipt * @param depositReceipt is the user's deposit receipt * @param currentRound is the `round` stored on the vault * @param assetPerShare is the price in asset per share * @param decimals is the number of decimals the asset/shares use * @return unredeemedShares is the user's virtual balance of shares that are owed */ function getSharesFromReceipt( Vault.DepositReceipt memory depositReceipt, uint256 currentRound, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256 unredeemedShares) { if (depositReceipt.round > 0 && depositReceipt.round < currentRound) { uint256 sharesFromRound = assetToShares(depositReceipt.amount, assetPerShare, decimals); return uint256(depositReceipt.unredeemedShares).add(sharesFromRound); } return depositReceipt.unredeemedShares; } function pricePerShare( uint256 totalSupply, uint256 totalBalance, uint256 pendingAmount, uint256 decimals ) internal pure returns (uint256) { uint256 singleShare = 10**decimals; return totalSupply > 0 ? singleShare.mul(totalBalance.sub(pendingAmount)).div( totalSupply ) : singleShare; } /************************************************ * HELPERS ***********************************************/ function assertUint104(uint256 num) internal pure { require(num <= type(uint104).max, "Overflow uint104"); } function assertUint128(uint256 num) internal pure { require(num <= type(uint128).max, "Overflow uint128"); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {Vault} from "../../../libraries/Vault.sol"; import {VaultLifecycle} from "../../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../../libraries/ShareMath.sol"; import {IWETH} from "../../../interfaces/IWETH.sol"; contract RibbonVault is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; /************************************************ * NON UPGRADEABLE STORAGE ***********************************************/ /// @notice Stores the user's pending deposit for the round mapping(address => Vault.DepositReceipt) public depositReceipts; /// @notice On every round's close, the pricePerShare value of an rTHETA token is stored /// This is used to determine the number of shares to be returned /// to a user with their DepositReceipt.depositAmount mapping(uint256 => uint256) public roundPricePerShare; /// @notice Stores pending user withdrawals mapping(address => Vault.Withdrawal) public withdrawals; /// @notice Vault's parameters like cap, decimals Vault.VaultParams public vaultParams; /// @notice Vault's lifecycle state like round and locked amounts Vault.VaultState public vaultState; /// @notice Vault's state of the options sold and the timelocked option Vault.OptionState public optionState; /// @notice Fee recipient for the performance and management fees address public feeRecipient; /// @notice role in charge of weekly vault operations such as rollToNextOption and burnRemainingOTokens // no access to critical vault changes address public keeper; /// @notice Performance fee charged on premiums earned in rollToNextOption. Only charged when there is no loss. uint256 public performanceFee; /// @notice Management fee charged on entire AUM in rollToNextOption. Only charged when there is no loss. uint256 public managementFee; // Gap is left to avoid storage collisions. Though RibbonVault is not upgradeable, we add this as a safety measure. uint256[30] private ____gap; // *IMPORTANT* NO NEW STORAGE VARIABLES SHOULD BE ADDED HERE // This is to prevent storage collisions. All storage variables should be appended to RibbonThetaVaultStorage // or RibbonDeltaVaultStorage instead. Read this documentation to learn more: // https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice WETH9 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 address public immutable WETH; /// @notice USDC 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 address public immutable USDC; /// @notice 1 hour timelock between commitAndClose and rollToNexOption. /// 1 hour period allows vault depositors to leave. uint256 public constant DELAY = 1 hours; /// @notice 7 day period between each options sale. uint256 public constant PERIOD = 7 days; // Number of weeks per year = 52.142857 weeks * FEE_MULTIPLIER = 52142857 // Dividing by weeks per year requires doing num.mul(FEE_MULTIPLIER).div(WEEKS_PER_YEAR) uint256 private constant WEEKS_PER_YEAR = 52142857; // GAMMA_CONTROLLER is the top-level contract in Gamma protocol // which allows users to perform multiple actions on their vaults // and positions https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/Controller.sol address public immutable GAMMA_CONTROLLER; // MARGIN_POOL is Gamma protocol's collateral pool. // Needed to approve collateral.safeTransferFrom for minting otokens. // https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/MarginPool.sol address public immutable MARGIN_POOL; // GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids // https://github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol address public immutable GNOSIS_EASY_AUCTION; /************************************************ * EVENTS ***********************************************/ event Deposit(address indexed account, uint256 amount, uint256 round); event InitiateWithdraw( address indexed account, uint256 shares, uint256 round ); event Redeem(address indexed account, uint256 share, uint256 round); event ManagementFeeSet(uint256 managementFee, uint256 newManagementFee); event PerformanceFeeSet(uint256 performanceFee, uint256 newPerformanceFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); event Withdraw(address indexed account, uint256 amount, uint256 shares); event CollectVaultFees( uint256 performanceFee, uint256 vaultFee, uint256 round, address indexed feeRecipient ); /************************************************ * CONSTRUCTOR & INITIALIZATION ***********************************************/ /** * @notice Initializes the contract with immutable variables * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _gammaController is the contract address for opyn actions * @param _marginPool is the contract address for providing collateral to opyn * @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions */ constructor( address _weth, address _usdc, address _gammaController, address _marginPool, address _gnosisEasyAuction ) { require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_gnosisEasyAuction != address(0), "!_gnosisEasyAuction"); require(_gammaController != address(0), "!_gammaController"); require(_marginPool != address(0), "!_marginPool"); WETH = _weth; USDC = _usdc; GAMMA_CONTROLLER = _gammaController; MARGIN_POOL = _marginPool; GNOSIS_EASY_AUCTION = _gnosisEasyAuction; } /** * @notice Initializes the OptionVault contract with storage variables. */ function baseInitialize( address _owner, address _keeper, address _feeRecipient, uint256 _managementFee, uint256 _performanceFee, string memory _tokenName, string memory _tokenSymbol, Vault.VaultParams calldata _vaultParams ) internal initializer { VaultLifecycle.verifyInitializerParams( _owner, _keeper, _feeRecipient, _performanceFee, _managementFee, _tokenName, _tokenSymbol, _vaultParams ); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); keeper = _keeper; feeRecipient = _feeRecipient; performanceFee = _performanceFee; managementFee = _managementFee.mul(Vault.FEE_MULTIPLIER).div( WEEKS_PER_YEAR ); vaultParams = _vaultParams; uint256 assetBalance = IERC20(vaultParams.asset).balanceOf(address(this)); ShareMath.assertUint104(assetBalance); vaultState.lastLockedAmount = uint104(assetBalance); vaultState.round = 1; } /** * @dev Throws if called by any account other than the keeper. */ modifier onlyKeeper() { require(msg.sender == keeper, "!keeper"); _; } /************************************************ * SETTERS ***********************************************/ /** * @notice Sets the new keeper * @param newKeeper is the address of the new keeper */ function setNewKeeper(address newKeeper) external onlyOwner { require(newKeeper != address(0), "!newKeeper"); keeper = newKeeper; } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); require(newFeeRecipient != feeRecipient, "Must be new feeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the management fee for the vault * @param newManagementFee is the management fee (6 decimals). ex: 2 * 10 ** 6 = 2% */ function setManagementFee(uint256 newManagementFee) external onlyOwner { require( newManagementFee < 100 * Vault.FEE_MULTIPLIER, "Invalid management fee" ); // We are dividing annualized management fee by num weeks in a year managementFee = newManagementFee.mul(Vault.FEE_MULTIPLIER).div( WEEKS_PER_YEAR ); } /** * @notice Sets the performance fee for the vault * @param newPerformanceFee is the performance fee (6 decimals). ex: 20 * 10 ** 6 = 20% */ function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner { require( newPerformanceFee < 100 * Vault.FEE_MULTIPLIER, "Invalid performance fee" ); emit PerformanceFeeSet(performanceFee, newPerformanceFee); performanceFee = newPerformanceFee; } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyOwner { require(newCap > 0, "!newCap"); ShareMath.assertUint104(newCap); vaultParams.cap = uint104(newCap); } /************************************************ * DEPOSIT & WITHDRAWALS ***********************************************/ /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the asset is not WETH. */ function depositETH() external payable nonReentrant { require(vaultParams.asset == WETH, "!WETH"); require(msg.value > 0, "!value"); _depositFor(msg.value, msg.sender); IWETH(WETH).deposit{value: msg.value}(); } /** * @notice Deposits the `asset` from msg.sender. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { require(amount > 0, "!amount"); _depositFor(amount, msg.sender); // An approve() by the msg.sender is required beforehand IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } /** * @notice Deposits the `asset` from msg.sender added to `creditor`'s deposit. * @notice Used for vault -> vault deposits on the user's behalf * @param amount is the amount of `asset` to deposit * @param creditor is the address that can claim/withdraw deposited amount */ function depositFor(uint256 amount, address creditor) external nonReentrant { require(amount > 0, "!amount"); require(creditor != address(0)); _depositFor(amount, creditor); // An approve() by the msg.sender is required beforehand IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } /** * @notice Mints the vault shares to the creditor * @param amount is the amount of `asset` deposited * @param creditor is the address to receieve the deposit */ function _depositFor(uint256 amount, address creditor) private { uint256 currentRound = vaultState.round; uint256 totalWithDepositedAmount = totalBalance().add(amount); require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap"); require( totalWithDepositedAmount >= vaultParams.minimumSupply, "Insufficient balance" ); emit Deposit(creditor, amount, currentRound); Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor]; // If we have an unprocessed pending deposit from the previous rounds, we have to process it. uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount; // If we have a pending deposit in the current round, we add on to the pending deposit if (currentRound == depositReceipt.round) { uint256 newAmount = uint256(depositReceipt.amount).add(amount); depositAmount = newAmount; } ShareMath.assertUint104(depositAmount); depositReceipts[creditor] = Vault.DepositReceipt({ round: uint16(currentRound), amount: uint104(depositAmount), unredeemedShares: uint128(unredeemedShares) }); uint256 newTotalPending = uint256(vaultState.totalPending).add(amount); ShareMath.assertUint128(newTotalPending); vaultState.totalPending = uint128(newTotalPending); } /** * @notice Initiates a withdrawal that can be processed once the round completes * @param numShares is the number of shares to withdraw */ function initiateWithdraw(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); // We do a max redeem before initiating a withdrawal // But we check if they must first have unredeemed shares if ( depositReceipts[msg.sender].amount > 0 || depositReceipts[msg.sender].unredeemedShares > 0 ) { _redeem(0, true); } // This caches the `round` variable used in shareBalances uint256 currentRound = vaultState.round; Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares; if (withdrawalIsSameRound) { withdrawalShares = existingShares.add(numShares); } else { require(existingShares == 0, "Existing withdraw"); withdrawalShares = numShares; withdrawals[msg.sender].round = uint16(currentRound); } ShareMath.assertUint128(withdrawalShares); withdrawals[msg.sender].shares = uint128(withdrawalShares); uint256 newQueuedWithdrawShares = uint256(vaultState.queuedWithdrawShares).add(numShares); ShareMath.assertUint128(newQueuedWithdrawShares); vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares); _transfer(msg.sender, address(this), numShares); } /** * @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round */ function completeWithdraw() external nonReentrant { Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; uint256 withdrawalShares = withdrawal.shares; uint256 withdrawalRound = withdrawal.round; // This checks if there is a withdrawal require(withdrawalShares > 0, "Not initiated"); require(withdrawalRound < vaultState.round, "Round not closed"); // We leave the round number as non-zero to save on gas for subsequent writes withdrawals[msg.sender].shares = 0; vaultState.queuedWithdrawShares = uint128( uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares) ); uint256 withdrawAmount = ShareMath.sharesToAsset( withdrawalShares, roundPricePerShare[withdrawalRound], vaultParams.decimals ); emit Withdraw(msg.sender, withdrawAmount, withdrawalShares); _burn(address(this), withdrawalShares); require(withdrawAmount > 0, "!withdrawAmount"); transferAsset(msg.sender, withdrawAmount); } /** * @notice Redeems shares that are owed to the account * @param numShares is the number of shares to redeem */ function redeem(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); _redeem(numShares, false); } /** * @notice Redeems the entire unredeemedShares balance that is owed to the account */ function maxRedeem() external nonReentrant { _redeem(0, true); } /** * @notice Redeems shares that are owed to the account * @param numShares is the number of shares to redeem, could be 0 when isMax=true * @param isMax is flag for when callers do a max redemption */ function _redeem(uint256 numShares, bool isMax) internal { Vault.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; // This handles the null case when depositReceipt.round = 0 // Because we start with round = 1 at `initialize` uint256 currentRound = vaultState.round; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); numShares = isMax ? unredeemedShares : numShares; if (numShares == 0) { return; } require(numShares <= unredeemedShares, "Exceeds available"); // If we have a depositReceipt on the same round, BUT we have some unredeemed shares // we debit from the unredeemedShares, but leave the amount field intact // If the round has past, with no new deposits, we just zero it out for new deposits. depositReceipts[msg.sender].amount = depositReceipt.round < currentRound ? 0 : depositReceipt.amount; ShareMath.assertUint128(numShares); depositReceipts[msg.sender].unredeemedShares = uint128( unredeemedShares.sub(numShares) ); emit Redeem(msg.sender, numShares, depositReceipt.round); _transfer(address(this), msg.sender, numShares); } /************************************************ * VAULT OPERATIONS ***********************************************/ /* * @notice Helper function that helps to save gas for writing values into the roundPricePerShare map. * Writing `1` into the map makes subsequent writes warm, reducing the gas from 20k to 5k. * Having 1 initialized beforehand will not be an issue as long as we round down share calculations to 0. * @param numRounds is the number of rounds to initialize in the map */ function initRounds(uint256 numRounds) external nonReentrant { require(numRounds > 0, "!numRounds"); uint256 _round = vaultState.round; for (uint256 i = 0; i < numRounds; i++) { uint256 index = _round + i; require(index >= _round, "Overflow"); require(roundPricePerShare[index] == 0, "Initialized"); // AVOID OVERWRITING ACTUAL VALUES roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT; } } /* * @notice Helper function that performs most administrative tasks * such as setting next option, minting new shares, getting vault fees, etc. * @return newOption is the new option address * @return lockedBalance is the new balance used to calculate next option purchase size or collateral size */ function _rollToNextOption() internal returns (address newOption, uint256 lockedBalance) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); (uint256 _lockedBalance, uint256 newPricePerShare, uint256 mintShares) = VaultLifecycle.rollover( totalSupply(), vaultParams.asset, vaultParams.decimals, uint256(vaultState.totalPending), vaultState.queuedWithdrawShares ); optionState.currentOption = newOption; optionState.nextOption = address(0); // Finalize the pricePerShare at the end of the round uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; // Take management / performance fee from previous round and deduct lockedBalance = _lockedBalance.sub(_collectVaultFees(_lockedBalance)); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); _mint(address(this), mintShares); return (newOption, lockedBalance); } /* * @notice Helper function that transfers management fees and performance fees from previous round. * @param currentLockedBalance is the balance we are about to lock for next round * @return vaultFee is the fee deducted */ function _collectVaultFees(uint256 currentLockedBalance) internal returns (uint256) { uint256 prevLockedAmount = vaultState.lastLockedAmount; uint256 lockedBalanceSansPending = currentLockedBalance.sub(vaultState.totalPending); uint256 vaultFee; uint256 performanceFeeInAsset; // Take performance fee and management fee ONLY if difference between // last week and this week's vault deposits, taking into account pending // deposits and withdrawals, is positive. If it is negative, last week's // option expired ITM past breakeven, and the vault took a loss so we // do not collect performance fee for last week if (lockedBalanceSansPending > prevLockedAmount) { performanceFeeInAsset = performanceFee > 0 ? lockedBalanceSansPending .sub(prevLockedAmount) .mul(performanceFee) .div(100 * Vault.FEE_MULTIPLIER) : 0; uint256 managementFeeInAsset = managementFee > 0 ? currentLockedBalance.mul(managementFee).div( 100 * Vault.FEE_MULTIPLIER ) : 0; vaultFee = performanceFeeInAsset.add(managementFeeInAsset); } if (vaultFee > 0) { transferAsset(payable(feeRecipient), vaultFee); emit CollectVaultFees( performanceFeeInAsset, vaultFee, vaultState.round, feeRecipient ); } return vaultFee; } /** * @notice Helper function to make either an ETH transfer or ERC20 transfer * @param recipient is the receiving address * @param amount is the transfer amount */ function transferAsset(address recipient, uint256 amount) internal { address asset = vaultParams.asset; if (asset == WETH) { IWETH(WETH).withdraw(amount); (bool success, ) = recipient.call{value: amount}(""); require(success, "Transfer failed"); return; } IERC20(asset).safeTransfer(recipient, amount); } /************************************************ * GETTERS ***********************************************/ /** * @notice Returns the asset balance held on the vault for the account * @param account is the address to lookup balance for * @return the amount of `asset` custodied by the vault for the user */ function accountVaultBalance(address account) external view returns (uint256) { uint256 _decimals = vaultParams.decimals; uint256 assetPerShare = ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, _decimals ); return ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals); } /** * @notice Getter for returning the account's share balance including unredeemed shares * @param account is the account to lookup share balance for * @return the share balance */ function shares(address account) public view returns (uint256) { (uint256 heldByAccount, uint256 heldByVault) = shareBalances(account); return heldByAccount.add(heldByVault); } /** * @notice Getter for returning the account's share balance split between account and vault holdings * @param account is the account to lookup share balance for * @return heldByAccount is the shares held by account * @return heldByVault is the shares held on the vault (unredeemedShares) */ function shareBalances(address account) public view returns (uint256 heldByAccount, uint256 heldByVault) { Vault.DepositReceipt memory depositReceipt = depositReceipts[account]; if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) { return (balanceOf(account), 0); } uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( vaultState.round, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); return (balanceOf(account), unredeemedShares); } /** * @notice The price of a unit of share denominated in the `asset` */ function pricePerShare() external view returns (uint256) { return ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, vaultParams.decimals ); } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return uint256(vaultState.lockedAmount).add( IERC20(vaultParams.asset).balanceOf(address(this)) ); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return vaultParams.decimals; } function cap() external view returns (uint256) { return vaultParams.cap; } function nextOptionReadyAt() external view returns (uint256) { return optionState.nextOptionReadyAt; } function currentOption() external view returns (address) { return optionState.currentOption; } function nextOption() external view returns (address) { return optionState.nextOption; } function totalPending() external view returns (uint256) { return vaultState.totalPending; } /************************************************ * HELPERS ***********************************************/ } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; library DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } 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; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 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); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AuctionType { struct AuctionData { IERC20 auctioningToken; IERC20 biddingToken; uint256 orderCancellationEndDate; uint256 auctionEndDate; bytes32 initialAuctionOrder; uint256 minimumBiddingAmountPerOrder; uint256 interimSumBidAmount; bytes32 interimOrder; bytes32 clearingPriceOrder; uint96 volumeClearingPriceOrder; bool minFundingThresholdNotReached; bool isAtomicClosureAllowed; uint256 feeNumerator; uint256 minFundingThreshold; } } interface IGnosisAuction { function initiateAuction( address _auctioningToken, address _biddingToken, uint256 orderCancellationEndDate, uint256 auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 minimumBiddingAmountPerOrder, uint256 minFundingThreshold, bool isAtomicClosureAllowed, address accessManagerContract, bytes memory accessManagerContractData ) external returns (uint256); function auctionCounter() external view returns (uint256); function auctionData(uint256 auctionId) external view returns (AuctionType.AuctionData memory); function auctionAccessManager(uint256 auctionId) external view returns (address); function auctionAccessData(uint256 auctionId) external view returns (bytes memory); function FEE_DENOMINATOR() external view returns (uint256); function feeNumerator() external view returns (uint256); function settleAuction(uint256 auctionId) external returns (bytes32); function placeSellOrders( uint256 auctionId, uint96[] memory _minBuyAmounts, uint96[] memory _sellAmounts, bytes32[] memory _prevSellOrders, bytes calldata allowListCallData ) external returns (uint64); function claimFromParticipantOrder( uint256 auctionId, bytes32[] memory orders ) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library GammaTypes { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral // in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } interface IOtoken { function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); } interface IOtokenFactory { function getOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); function createOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external returns (address); function getTargetOtokenAddress( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); event OtokenCreated( address tokenAddress, address creator, address indexed underlying, address indexed strike, address indexed collateral, uint256 strikePrice, uint256 expiry, bool isPut ); } interface IController { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets // but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function operate(ActionArgs[] calldata _actions) external; function getAccountVaultCounter(address owner) external view returns (uint256); function oracle() external view returns (address); function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory); function getProceed(address _owner, uint256 _vaultId) external view returns (uint256); function isSettlementAllowed( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IStrikeSelection { function getStrikePrice(uint256 expiryTimestamp, bool isPut) external view returns (uint256, uint256); function delta() external view returns (uint256); } interface IOptionsPremiumPricer { function getPremium( uint256 strikePrice, uint256 timeToExpiry, bool isPut ) external view returns (uint256); function getOptionDelta( uint256 spotPrice, uint256 strikePrice, uint256 volatility, uint256 expiryTimestamp ) external view returns (uint256 delta); function getUnderlyingPrice() external view returns (uint256); function priceOracle() external view returns (address); function volatilityOracle() external view returns (address); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {Vault} from "../libraries/Vault.sol"; interface IRibbonThetaVault { function currentOption() external view returns (address); function nextOption() external view returns (address); function vaultParams() external view returns (Vault.VaultParams memory); function vaultState() external view returns (Vault.VaultState memory); function optionState() external view returns (Vault.OptionState memory); function optionAuctionID() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Detailed is IERC20 { function decimals() external view returns (uint8); function symbol() external view returns (string calldata); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * This library supports ERC20s that have quirks in their behavior. * One such ERC20 is USDT, which requires allowance to be 0 before calling approve. * We plan to update this library with ERC20s that display such idiosyncratic behavior. */ library SupportsNonCompliantERC20 { address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; function safeApproveNonCompliant( IERC20 token, address spender, uint256 amount ) internal { if (address(token) == USDT) { SafeERC20.safeApprove(token, spender, 0); } SafeERC20.safeApprove(token, spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/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.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
Helper function that performs most administrative tasks such as setting next option, minting new shares, getting vault fees, etc. return newOption is the new option address return lockedBalance is the new balance used to calculate next option purchase size or collateral size/ Finalize the pricePerShare at the end of the round Take management / performance fee from previous round and deduct
function _rollToNextOption() internal returns (address newOption, uint256 lockedBalance) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); (uint256 _lockedBalance, uint256 newPricePerShare, uint256 mintShares) = VaultLifecycle.rollover( totalSupply(), vaultParams.asset, vaultParams.decimals, uint256(vaultState.totalPending), vaultState.queuedWithdrawShares ); optionState.currentOption = newOption; optionState.nextOption = address(0); uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; lockedBalance = _lockedBalance.sub(_collectVaultFees(_lockedBalance)); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); _mint(address(this), mintShares); return (newOption, lockedBalance); }
6,090,112
pragma solidity >= 0.6.2; import 'TwicyStorage.sol'; import 'interfaces/TwicyInterface.sol'; import 'modifiers/MigrationModifier.sol'; import 'modifiers/TransferValueModifier.sol'; import 'utils/ArrayUtil.sol'; import 'utils/HexadecimalNumberUtil.sol'; import 'utils/MessageUtil.sol'; import 'utils/PseudoRandomUtil.sol'; import 'utils/TextUtil.sol'; import 'utils/TwicyRewardUtil.sol'; /** * ████████╗██╗ ██╗██╗ ██████╗██╗ ██╗ * ╚══██╔══╝██║ ██║██║██╔════╝╚██╗ ██╔╝ * ██║ ██║ █╗ ██║██║██║ ╚████╔╝ * ██║ ██║███╗██║██║██║ ╚██╔╝ * ██║ ╚███╔███╔╝██║╚██████╗ ██║ * ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═════╝ ╚═╝ * First risk-game on Free TON * * Error codes * • 100 — Method only for the owner * • 101 — Method only for storage * • 102 — Invalid deposit value * • 103 — More storages are required * • 104 — Invalid referral id * • 105 — Invalid storage address * • 200 — Invalid transfer value * • 300 — Method can only be called before migration * • 301 — Method can only be called after migration */ contract Twicy is TwicyInterface, MigrationModifier, TransferValueModifier, ArrayUtil, HexadecimalNumberUtil, MessageUtil, PseudoRandomUtil, TextUtil, TwicyRewardUtil { /************* * CONSTANTS * *************/ uint8 private constant DEFAULT_DEPLOYED_STORAGES = 2; uint128 private constant STORAGE_DEPLOY_VALUE = 1e9; // 1💎 uint128 private constant STORAGE_TRANSFER_VALUE = 0.2e9; // 0.2💎 uint128 private constant CONFIRMATION_VALUE = 0.001e9; // 0.001💎 uint128 private constant DEPOSIT = 10e9; // 10💎 /************* * VARIABLES * *************/ TvmCell private _storageCode; uint32 private _storageLength; address[] private _storageAddresses; uint128[] private _storageAmounts; uint32 private _storageIdForPayout; uint64 private _depositsCount; uint256 private _total; mapping(address => bool) _storages; /************* * MODIFIERS * *************/ modifier accept { tvm.accept(); _; } modifier onlyOwner { require(msg.pubkey() == tvm.pubkey(), 100, "Method only for owner"); _; } modifier onlyStorage() { require(_storages.exists(msg.sender), 101, "Method only for storage"); _; } modifier validDeposit() { require(msg.value == DEPOSIT, 102, "Invalid deposit value"); _; } modifier enoughStorages() { require(getDepositsLimit() >= _depositsCount, 103, "More storages are required"); _; } modifier validReferralId(uint64 referrerId) { require(referrerId < _depositsCount, 104, "Invalid referral id"); _; } modifier validStorage(address storageAddress) { require(_storages.exists(storageAddress), 105, "Invalid storage address"); _; } /*************** * CONSTRUCTOR * ***************/ constructor(TvmCell storageCode,uint32 storageLength) public accept { _storageCode = storageCode; _storageLength = storageLength; _saveText(); deployStorage(DEFAULT_DEPLOYED_STORAGES); } /*********** * GETTERS * ***********/ function getStorageLength() public view returns (uint32 storageLength) { return _storageLength; } function getStorageIdForPayout() public view returns (uint32 storageIdForPayout) { return _storageIdForPayout; } function getDepositsCount() public view returns (uint64 depositsCount) { return _depositsCount; } function getTotal() public view returns (uint256 total) { return _total; } function getDepositsLimit() public view returns (uint64 depositLimit) { return uint64(_storageLength * _storageAddresses.length); } function getStorages(uint32 offset, uint32 limit) public view returns ( address[] addresses, uint128[] amounts, uint256 totalLength ) { address[] storageAddresses = _storageAddresses; uint128[] storageAmounts = _storageAmounts; uint64 endIndex = _getEndIndex(offset, limit, storageAddresses.length); for (uint64 i = offset; i < endIndex; i++) { addresses.push(storageAddresses[i]); amounts.push(storageAmounts[i]); } return (addresses, amounts, storageAddresses.length); } /*********************** * PUBLIC * ONLY OWNER * ***********************/ function deployStorage(uint8 count) public onlyOwner accept returns (address[] addresses) { address[] storageAddresses = _storageAddresses; uint128[] storageAmounts = _storageAmounts; mapping(address => bool) storages = _storages; address rootAddress = address(this); for (uint8 i = 0; i < count; i++) { uint256 random = _getRandom(i); TvmCell storageData = tvm.buildEmptyData(random); TvmCell stateInit = tvm.buildStateInit(_storageCode, storageData); address storageAddress = new TwicyStorage{stateInit: stateInit, value: STORAGE_DEPLOY_VALUE}(rootAddress); storageAddresses.push(storageAddress); storageAmounts.push(0); storages[storageAddress] = true; addresses.push(storageAddress); } _storageAddresses = storageAddresses; _storageAmounts = storageAmounts; _storages = storages; return addresses; } function sendTransaction( address destination, uint128 value ) public view onlyOwner accept validTransferValue(value) { destination.transfer(value); } function storageSendTransaction( address storageAddress, address destination, uint128 value ) public view onlyOwner accept validStorage(storageAddress) { TwicyStorage(storageAddress).sendTransaction(destination, value); } /*********************************** * PUBLIC * ONLY OWNER * MIGRATION * ***********************************/ function migrate( uint128[] storageAmounts, uint32 storageIdForPayout, uint64 depositsCount, uint256 total ) public onlyOwner accept beforeMigration { _storageAmounts = storageAmounts; _storageIdForPayout = storageIdForPayout; _depositsCount = depositsCount; _total = total; } function migrateStorage( address storageAddress, uint128 amountAvailableForPayout, uint32 payoutsCount ) public onlyOwner accept beforeMigration { TwicyStorage(storageAddress).migrate{value: 1e9}(amountAvailableForPayout, payoutsCount); } function migrateStorageDeposits( address storageAddress, address[] senders, uint128[] rewards ) public onlyOwner accept beforeMigration { TwicyStorage(storageAddress).migrateDeposits{value: 1e9}(senders, rewards); } function completeMigration() public onlyOwner beforeMigration accept { _migrationCompleted = true; } /******************** * PUBLIC * DEPOSIT * ********************/ function depositWithReferralId(uint64 referralId) public validDeposit enoughStorages afterMigration { address sender = msg.sender; uint128 value = uint128(msg.value); _dispatchReferrerAddress(sender, value, referralId); } function deposit() public validDeposit enoughStorages afterMigration { address sender = msg.sender; uint128 value = uint128(msg.value); _depositWithoutReferralBonus(sender, value); } /************ * EXTERNAL * ************/ function onReceiveReferrerAddress(address sender, address referrer, uint128 value) external override onlyStorage { if (sender == referrer) _depositWithoutReferralBonus(sender, value); else { uint128 referrerPayout = _getReferrerPayout(value); referrer.transfer({value: referrerPayout, body: _getTransferBody(TEXT_REFERRAL)}); _depositWithReferralBonus(sender, value); } } function onReceiveDepositsForPayout(address[] owners, uint128[] rewards) external override onlyStorage { for (uint64 i = 0; i < owners.length; i++) { address owner = owners[i]; uint128 reward = rewards[i]; owner.transfer({value: reward, body: _getTransferBody(TEXT_REWARD)}); } } /*********** * RECEIVE * ***********/ receive() external validDeposit enoughStorages afterMigration { address sender = msg.sender; uint128 value = uint128(msg.value); uint8[] message = _readMessage(msg.data); /////////////////////////////////////// // 1. "bank" comment // // Just increase contract balance // /////////////////////////////////////// if (_messageIsEqual(message, TEXT_BANK)) _receiveBank(sender); //////////////////////////////////////// // 2. Deposit id in comment // // Examples: "0x0", "0x3F", "0x34" // //////////////////////////////////////// else if (_messageIsHexadecimalNumber(message)) _receiveDepositWithReferralId(sender, value, message); ////////////////////////// // 3. Any other comment // ////////////////////////// else _receiveDeposit(sender, value); } function _receiveBank(address sender) private view { sender.transfer({value: CONFIRMATION_VALUE, body: _getTransferBody(TEXT_OK)}); } function _receiveDepositWithReferralId(address sender, uint128 value, uint8[] message) private { uint64 referralId = _readHexadecimalNumberFromMessage(message); _dispatchReferrerAddress(sender, value, referralId); } function _receiveDeposit(address sender, uint128 value) private { _depositWithoutReferralBonus(sender, value); } /*********** * PRIVATE * ***********/ function _dispatchReferrerAddress(address sender, uint128 value, uint64 referralId) private validReferralId(referralId) { uint32 storageId = _getStorageId(referralId); address storageAddress = _storageAddresses[storageId]; uint32 index = uint32(referralId % _storageLength); TwicyStorage(storageAddress).dispatchReferrerAddress{value: STORAGE_TRANSFER_VALUE}(sender, value, index); } function _getStorageId(uint64 depositId) private view returns(uint32) { return uint32(depositId / _storageLength); } function _depositWithReferralBonus(address sender, uint128 value) private { uint128 reward = _getBonusReward(value); uint128 payout = _getBonusUsersPayout(value); _deposit(sender, value, reward, payout); } function _depositWithoutReferralBonus(address sender, uint128 value) private { uint128 reward = _getRegularReward(value); uint128 payout = _getRegularUsersPayout(value); _deposit(sender, value, reward, payout); } function _deposit(address sender, uint128 value, uint128 reward, uint128 payoutValue) private { _depositConfirmation(sender); _save(sender, value, reward); _dispatchDepositsForPayout(payoutValue); } function _depositConfirmation(address sender) private view { uint8[] message = _getMessageWithHexadecimalNumber(_depositsCount); sender.transfer({value: CONFIRMATION_VALUE, body: _getTransferBody(message)}); } function _save(address sender, uint128 value, uint128 reward) private { uint32 storageId = _getStorageId(_depositsCount); address storageAddress = _storageAddresses[storageId]; TwicyStorage(storageAddress).save{value: STORAGE_TRANSFER_VALUE}(sender, reward); _storageAmounts[storageId] += reward; _total += value; _depositsCount++; } function _dispatchDepositsForPayout(uint128 payoutValue) private { address[] storageAddresses = _storageAddresses; uint128[] storageAmounts = _storageAmounts; uint32 storageIdForPayout = _storageIdForPayout; for (uint64 i = storageIdForPayout; i < storageAddresses.length; i++) { address storageAddress = storageAddresses[i]; uint128 storageAmount = storageAmounts[i]; if (payoutValue >= storageAmount) { payoutValue -= storageAmount; storageAmounts[i] = 0; TwicyStorage(storageAddress).dispatchDepositsForPayout{value: STORAGE_TRANSFER_VALUE}(storageAmount); storageIdForPayout++; } else { storageAmounts[i] -= payoutValue; TwicyStorage(storageAddress).dispatchDepositsForPayout{value: STORAGE_TRANSFER_VALUE}(payoutValue); break; } } _storageAmounts = storageAmounts; _storageIdForPayout = storageIdForPayout; } }
PUBLIC DEPOSIT /
function depositWithReferralId(uint64 referralId) public validDeposit enoughStorages afterMigration { address sender = msg.sender; uint128 value = uint128(msg.value); _dispatchReferrerAddress(sender, value, referralId); }
1,777,267
./partial_match/84531/0x21F359D1869314175d84A18A6F5DEb94672C4996/sources/RequestManager.sol
OpenZeppelin: changed return type from IOwnable ---------- onlySequencerInbox functions ---------- ---------- onlyRollupOrOwner functions ---------- ---------- initializer ---------- OpenZeppelin: changed rollup_ type from IOwnable
interface IBridge { event MessageDelivered( uint256 indexed messageIndex, bytes32 indexed beforeInboxAcc, address inbox, uint8 kind, address sender, bytes32 messageDataHash, uint256 baseFeeL1, uint64 timestamp ); event BridgeCallTriggered(address indexed outbox, address indexed to, uint256 value, bytes data); event InboxToggle(address indexed inbox, bool enabled); event OutboxToggle(address indexed outbox, bool enabled); event SequencerInboxUpdated(address newSequencerInbox); function allowedDelayedInboxList(uint256) external returns (address); function allowedOutboxList(uint256) external returns (address); function delayedInboxAccs(uint256) external view returns (bytes32); function sequencerInboxAccs(uint256) external view returns (bytes32); function rollup() external view returns (address); function sequencerInbox() external view returns (address); function activeOutbox() external view returns (address); function allowedDelayedInboxes(address inbox) external view returns (bool); function allowedOutboxes(address outbox) external view returns (bool); function sequencerReportedSubMessageCount() external view returns (uint256); function enqueueDelayedMessage( uint8 kind, address sender, bytes32 messageDataHash ) external payable returns (uint256); function executeCall( address to, uint256 value, bytes calldata data ) external returns (bool success, bytes memory returnData); function delayedMessageCount() external view returns (uint256); function sequencerMessageCount() external view returns (uint256); function enqueueSequencerMessage( bytes32 dataHash, uint256 afterDelayedMessagesRead, uint256 prevMessageCount, uint256 newMessageCount ) external returns ( uint256 seqMessageIndex, bytes32 beforeAcc, bytes32 delayedAcc, bytes32 acc ); function submitBatchSpendingReport(address batchPoster, bytes32 dataHash) external returns (uint256 msgNum); function setSequencerInbox(address _sequencerInbox) external; function setDelayedInbox(address inbox, bool enabled) external; function setOutbox(address inbox, bool enabled) external; function initialize(address rollup_) external; } }
16,683,567
./full_match/1/0xBCF9F4c6FC589c89d4aAdE063010D0f5B3733680/sources/contracts/staking/Staking.sol
Stake tokens on the indexer. This function does not check minimum indexer stake requirement to allow to be called by functions that increase the stake when collecting rewards without reverting _indexer Address of staking party _tokens Amount of tokens to stake/ Deposit tokens into the indexer stake Initialize the delegation pool the first time
function _stake(address _indexer, uint256 _tokens) private { stakes[_indexer].deposit(_tokens); if (delegationPools[_indexer].updatedAtBlock == 0) { setDelegationParameters(MAX_PPM, MAX_PPM, delegationParametersCooldown); } emit StakeDeposited(_indexer, _tokens); }
4,905,299
pragma solidity ^0.4.18; // File: contracts/IPricingStrategy.sol interface IPricingStrategy { function isPricingStrategy() public view returns (bool); /** Calculate the current price for buy in amount. */ function calculateTokenAmount(uint weiAmount, uint tokensSold) public view returns (uint tokenAmount); } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/ERC223.sol contract ERC223 is ERC20 { function transfer(address _to, uint _value, bytes _data) public returns (bool); function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } // File: contracts/token/TokenReciever.sol /* * Contract that is working with ERC223 tokens */ contract TokenReciever { function tokenFallback(address _from, uint _value, bytes _data) public pure { } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/ownership/Contactable.sol /** * @title Contactable token * @dev Basic version of a contactable contract, allowing the owner to provide a string with their * contact information. */ contract Contactable is Ownable{ string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } } // File: contracts/token/PlayHallToken.sol contract PlayHallToken is ERC223, Contactable { using SafeMath for uint; string constant public name = "PlayHall Token"; string constant public symbol = "PHT"; uint constant public decimals = 18; bool public isActivated = false; mapping (address => uint) balances; mapping (address => mapping (address => uint)) internal allowed; mapping (address => bool) public freezedList; // address, who is allowed to issue new tokens (presale and sale contracts) address public minter; bool public mintingFinished = false; event Mint(address indexed to, uint amount); event MintingFinished(); modifier onlyMinter() { require(msg.sender == minter); _; } modifier canMint() { require(!mintingFinished); _; } modifier whenActivated() { require(isActivated); _; } function PlayHallToken() public { minter = msg.sender; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data Optional metadata. */ function transfer(address _to, uint _value, bytes _data) public whenActivated returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(!freezedList[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (isContract(_to)) { TokenReciever receiver = TokenReciever(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _value, empty); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred * @param _data Optional metadata. */ function transferFrom(address _from, address _to, uint _value, bytes _data) public whenActivated returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(!freezedList[_from]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); if (isContract(_to)) { TokenReciever receiver = TokenReciever(_to); receiver.tokenFallback(_from, _value, _data); } Transfer(_from, _to, _value); Transfer(_from, _to, _value, _data); 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&#39;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, uint _value) public returns (bool) { require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint _amount, bool freeze) canMint onlyMinter external returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); if (freeze) { freezedList[_to] = true; } Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() canMint onlyMinter external returns (bool) { mintingFinished = true; MintingFinished(); return true; } /** * Minter can pass it&#39;s role to another address */ function setMinter(address _minter) external onlyMinter { require(_minter != 0x0); minter = _minter; } /** * Owner can unfreeze any address */ function removeFromFreezedList(address user) external onlyOwner { freezedList[user] = false; } /** * Activation of the token allows all tokenholders to operate with the token */ function activate() external onlyOwner returns (bool) { isActivated = true; return true; } function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/SaleBase.sol contract SaleBase is Pausable, Contactable { using SafeMath for uint; // The token being sold PlayHallToken public token; // start and end timestamps where purchases are allowed (both inclusive) uint public startTime; uint public endTime; // address where funds are collected address public wallet; // the contract, which determine how many token units a buyer gets per wei IPricingStrategy public pricingStrategy; // amount of raised money in wei uint public weiRaised; // amount of tokens that was sold on the crowdsale uint public tokensSold; // maximum amount of wei in total, that can be bought uint public weiMaximumGoal; // if weiMinimumGoal will not be reached till endTime, buyers will be able to refund ETH uint public weiMinimumGoal; // minimum amount of wel, that can be contributed uint public weiMinimumAmount; // How many distinct addresses have bought uint public buyerCount; // how much wei we have returned back to the contract after a failed crowdfund uint public loadedRefund; // how much wei we have given back to buyers uint public weiRefunded; // how much ETH each address has bought to this crowdsale mapping (address => uint) public boughtAmountOf; // whether a buyer already bought some tokens mapping (address => bool) public isBuyer; // whether a buyer bought tokens through other currencies mapping (address => bool) public isExternalBuyer; address public admin; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param tokenAmount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint value, uint tokenAmount ); // a refund was processed for an buyer event Refund(address buyer, uint weiAmount); event RefundLoaded(uint amount); function SaleBase( uint _startTime, uint _endTime, IPricingStrategy _pricingStrategy, PlayHallToken _token, address _wallet, uint _weiMaximumGoal, uint _weiMinimumGoal, uint _weiMinimumAmount, address _admin ) public { require(_startTime >= now); require(_endTime >= _startTime); require(_pricingStrategy.isPricingStrategy()); require(address(_token) != 0x0); require(_wallet != 0x0); require(_weiMaximumGoal > 0); require(_admin != 0x0); startTime = _startTime; endTime = _endTime; pricingStrategy = _pricingStrategy; token = _token; wallet = _wallet; weiMaximumGoal = _weiMaximumGoal; weiMinimumGoal = _weiMinimumGoal; weiMinimumAmount = _weiMinimumAmount; admin = _admin; } modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == admin); _; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public whenNotPaused payable returns (bool) { uint weiAmount = msg.value; require(beneficiary != 0x0); require(weiAmount >= weiMinimumAmount); require(validPurchase(msg.value)); // calculate token amount to be created uint tokenAmount = pricingStrategy.calculateTokenAmount(weiAmount, weiRaised); mintTokenToBuyer(beneficiary, tokenAmount, weiAmount); wallet.transfer(msg.value); return true; } function mintTokenToBuyer(address beneficiary, uint tokenAmount, uint weiAmount) internal { if (!isBuyer[beneficiary]) { // A new buyer buyerCount++; isBuyer[beneficiary] = true; } boughtAmountOf[beneficiary] = boughtAmountOf[beneficiary].add(weiAmount); weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); token.mint(beneficiary, tokenAmount, true); TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount); } // return true if the transaction can buy tokens function validPurchase(uint weiAmount) internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool withinCap = weiRaised.add(weiAmount) <= weiMaximumGoal; return withinPeriod && withinCap; } // return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= weiMaximumGoal; bool afterEndTime = now > endTime; return capReached || afterEndTime; } // get the amount of unsold tokens allocated to this contract; function getWeiLeft() external constant returns (uint) { return weiMaximumGoal - weiRaised; } // return true if the crowdsale has raised enough money to be a successful. function isMinimumGoalReached() public constant returns (bool) { return weiRaised >= weiMinimumGoal; } // allows to update tokens rate for owner function setPricingStrategy(IPricingStrategy _pricingStrategy) external onlyOwner returns (bool) { pricingStrategy = _pricingStrategy; return true; } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.. */ function loadRefund() external payable { require(msg.sender == wallet); require(msg.value > 0); require(!isMinimumGoalReached()); loadedRefund = loadedRefund.add(msg.value); RefundLoaded(msg.value); } /** * Buyers can claim refund. * * Note that any refunds from proxy buyers should be handled separately, * and not through this contract. */ function refund() external { require(!isMinimumGoalReached() && loadedRefund > 0); require(!isExternalBuyer[msg.sender]); uint weiValue = boughtAmountOf[msg.sender]; require(weiValue > 0); boughtAmountOf[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); msg.sender.transfer(weiValue); Refund(msg.sender, weiValue); } function registerPayment(address beneficiary, uint tokenAmount, uint weiAmount) public onlyOwnerOrAdmin { require(validPurchase(weiAmount)); isExternalBuyer[beneficiary] = true; mintTokenToBuyer(beneficiary, tokenAmount, weiAmount); } function registerPayments(address[] beneficiaries, uint[] tokenAmounts, uint[] weiAmounts) external onlyOwnerOrAdmin { require(beneficiaries.length == tokenAmounts.length); require(tokenAmounts.length == weiAmounts.length); for (uint i = 0; i < beneficiaries.length; i++) { registerPayment(beneficiaries[i], tokenAmounts[i], weiAmounts[i]); } } function setAdmin(address adminAddress) external onlyOwner { admin = adminAddress; } } // File: contracts/presale/Presale.sol /** * @title Presale * @dev Presale is a contract for managing a token crowdsale. * Presales have a start and end timestamps, where buyers can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Presale is SaleBase { function Presale( uint _startTime, uint _endTime, IPricingStrategy _pricingStrategy, PlayHallToken _token, address _wallet, uint _weiMaximumGoal, uint _weiMinimumGoal, uint _weiMinimumAmount, address _admin ) public SaleBase( _startTime, _endTime, _pricingStrategy, _token, _wallet, _weiMaximumGoal, _weiMinimumGoal, _weiMinimumAmount, _admin) { } function changeTokenMinter(address newMinter) external onlyOwner { require(newMinter != 0x0); require(hasEnded()); token.setMinter(newMinter); } }
allows to update tokens rate for owner
function setPricingStrategy(IPricingStrategy _pricingStrategy) external onlyOwner returns (bool) { pricingStrategy = _pricingStrategy; return true; }
2,319,210
./full_match/10/0x6604de3C9E7D511894d05939EE0f7538965be066/sources/contracts/CommonArbitrageur.sol
check for deflationary tokens by assuring balances before and after transferring to be the same CA_IBA: inconsistent balance amount, to prevent from deflationary tokens
function _transferTokenIn( address token, address from, uint256 amount ) internal { uint256 balanceBefore = IERC20(token).balanceOf(address(this)); SafeERC20.safeTransferFrom(IERC20(token), from, address(this), amount); uint256 balanceNow = IERC20(token).balanceOf(address(this)); require(balanceNow > balanceBefore && (balanceNow - balanceBefore) == amount, "CA_IBA"); }
3,779,373
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.16; contract JoetrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, JOETROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, JOETROLLER_REJECTION, JOETROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_JOETROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_JOETROLLER_REJECTION, LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_JOETROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_JOETROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_JOETROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_JOETROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_JOETROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_JOETROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per sec * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per sec (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per sec * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per sec (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } contract PriceOracle { /** * @notice Get the underlying price of a jToken asset * @param jToken The jToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(JToken jToken) external view returns (uint256); } /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) { 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) { 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 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( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 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(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 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) internal pure returns (MathError, Exp memory) { (MathError error, uint256 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) internal pure returns (MathError, Exp memory) { (MathError error, uint256 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, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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, uint256 scalar) internal pure returns (MathError, uint256) { (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, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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(uint256 scalar, Exp memory divisor) internal pure 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, uint256 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(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (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` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 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, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 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(uint256 a, uint256 b) internal pure 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 ) internal pure 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) internal pure 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) internal pure returns (uint256) { // 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) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public joetrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingJoetrollerImplementation; } contract JoetrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => JToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice JToken version Version version; } /** * @notice Official mapping of jTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; /// @notice A list of all markets JToken[] public allMarkets; // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each jToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; // @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; // @notice Supply caps enforced by mintAllowed for each jToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; // @notice creditLimits allowed specific protocols to borrow and repay without collateral. mapping(address => uint256) public creditLimits; // @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; // @notice rewardDistributor The module that handles reward distribution. address payable public rewardDistributor; } contract JoetrollerInterface { /// @notice Indicator that this is a Joetroller contract (for inspection) bool public constant isJoetroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata jTokens) external returns (uint256[] memory); function exitMarket(address jToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address jToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address jToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address jToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address jToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address jToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address jToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address jToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address jToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address jTokenBorrowed, address jTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address jTokenBorrowed, address jTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address jTokenCollateral, address jTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address jTokenCollateral, address jTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address jToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address jToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address jTokenBorrowed, address jTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface JoetrollerInterfaceExtension { function checkMembership(address account, JToken jToken) external view returns (bool); function updateJTokenVersion(address jToken, JoetrollerV1Storage.Version version) external; function flashloanAllowed( address jToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); } contract JTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / sec) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-jToken operations */ JoetrollerInterface public joetroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first JTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block timestamp that interest was last accrued at */ uint256 public accrualBlockTimestamp; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract JErc20Storage { /** * @notice Underlying asset for this JToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract JSupplyCapStorage { /** * @notice Internal cash counter for this JToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract JCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this JToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract JTokenInterface is JTokenStorage { /** * @notice Indicator that this is a JToken contract (for inspection) */ bool public constant isJToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address jTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when joetroller is changed */ event NewJoetroller(JoetrollerInterface oldJoetroller, JoetrollerInterface newJoetroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerSecond() external view returns (uint256); function supplyRatePerSecond() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract JErc20Interface is JErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, JTokenInterface jTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract JWrappedNativeInterface is JErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function repayBorrowBehalfNative(address borrower) external payable returns (uint256); function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); } contract JCapableErc20Interface is JErc20Interface, JSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract JCollateralCapErc20Interface is JCapableErc20Interface, JCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract JDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract JDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @title Compound's JToken Contract * @notice Abstract base for JTokens * @author Compound */ contract JToken is JTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param joetroller_ The address of the Joetroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( JoetrollerInterface joetroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockTimestamp == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the joetroller uint256 err = _setJoetroller(joetroller_); require(err == uint256(Error.NO_ERROR), "setting joetroller failed"); // Initialize block timestamp and borrow index (block timestamp mocks depend on joetroller being set) accrualBlockTimestamp = getBlockTimestamp(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block timestamp / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by joetroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 jTokenBalance = getJTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), jTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block timestamp * This exists mainly for inheriting test contracts to stub this result. */ function getBlockTimestamp() internal view returns (uint256) { return block.timestamp; } /** * @notice Returns the current per-sec borrow interest rate for this jToken * @return The borrow interest rate per sec, scaled by 1e18 */ function borrowRatePerSecond() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-sec supply interest rate for this jToken * @return The supply interest rate per sec, scaled by 1e18 */ function supplyRatePerSecond() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-sec borrow interest rate for this jToken after some change * @return The borrow interest rate per sec, scaled by 1e18 */ function estimateBorrowRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-sec supply interest rate for this jToken after some change * @return The supply interest rate per sec, scaled by 1e18 */ function estimateSupplyRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the JToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the JToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this jToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed timestamp * up to the current timestamp and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block timestamp */ uint256 currentBlockTimestamp = getBlockTimestamp(); uint256 accrualBlockTimestampPrior = accrualBlockTimestamp; /* Short-circuit accumulating 0 interest */ if (accrualBlockTimestampPrior == currentBlockTimestamp) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of seconds elapsed since the last accrual */ uint256 timestampDelta = sub_(currentBlockTimestamp, accrualBlockTimestampPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * timestampDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), timestampDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockTimestamp = currentBlockTimestamp; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives jTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems jTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of jTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems jTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming jTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = joetroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.BORROW_JOETROLLER_REJECTION, allowed); } /* * Return if borrowAmount is zero. * Put behind `borrowAllowed` for accuring potential JOE rewards. */ if (borrowAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return uint256(Error.NO_ERROR); } /* Verify market's block timestamp equals current block timestamp */ if (accrualBlockTimestamp != getBlockTimestamp()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The jToken must handle variations between ERC-20 and ETH underlying. * On success, the jToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // joetroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = joetroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REPAY_BORROW_JOETROLLER_REJECTION, allowed), 0); } /* * Return if repayAmount is zero. * Put behind `repayBorrowAllowed` for accuring potential JOE rewards. */ if (repayAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return (uint256(Error.NO_ERROR), 0); } /* Verify market's block timestamp equals current block timestamp */ if (accrualBlockTimestamp != getBlockTimestamp()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The jToken must handle variations between ERC-20 and ETH underlying. * On success, the jToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // joetroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this jToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param jTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, JTokenInterface jTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = jTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, jTokenCollateral, isNative); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this jToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param jTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, JTokenInterface jTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = joetroller.liquidateBorrowAllowed( address(this), address(jTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_JOETROLLER_REJECTION, allowed), 0); } /* Verify market's block timestamp equals current block timestamp */ if (accrualBlockTimestamp != getBlockTimestamp()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify jTokenCollateral market's block timestamp equals current block timestamp */ if (jTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh( liquidator, borrower, repayAmount, isNative ); if (repayBorrowError != uint256(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint256 amountSeizeError, uint256 seizeTokens) = joetroller.liquidateCalculateSeizeTokens( address(this), address(jTokenCollateral), actualRepayAmount ); require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(jTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(jTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = jTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(jTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // joetroller.liquidateBorrowVerify(address(this), address(jTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint256(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another jToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of jTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new joetroller for the market * @dev Admin function to set a new joetroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_JOETROLLER_OWNER_CHECK); } JoetrollerInterface oldJoetroller = joetroller; // Ensure invoke joetroller.isJoetroller() returns true require(newJoetroller.isJoetroller(), "marker method returned false"); // Set market's joetroller to newJoetroller joetroller = newJoetroller; // Emit NewJoetroller(oldJoetroller, newJoetroller) emit NewJoetroller(oldJoetroller, newJoetroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block timestamp equals current block timestamp if (accrualBlockTimestamp != getBlockTimestamp()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block timestamp equals current block timestamp if (accrualBlockTimestamp != getBlockTimestamp()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The jToken must handle variations between ERC-20 and ETH underlying. * On success, the jToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block timestamp equals current block timestamp if (accrualBlockTimestamp != getBlockTimestamp()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in native token. Implementations except `JWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, true); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block timestamp equals current block timestamp if (accrualBlockTimestamp != getBlockTimestamp()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's jToken balances */ function getJTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives jTokens in exchange * @dev Assumes interest has already been accrued up to the current timestamp */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems jTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current timestamp */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken. * Its absolutely critical to use msg.sender as the seizer jToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma experimental ABIEncoderV2; contract RewardDistributorStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Active brains of Unitroller */ Joetroller public joetroller; struct RewardMarketState { /// @notice The market's last updated joeBorrowIndex or joeSupplyIndex uint224 index; /// @notice The timestamp number the index was last updated at uint32 timestamp; } /// @notice The portion of reward rate that each market currently receives mapping(uint8 => mapping(address => uint256)) public rewardSpeeds; /// @notice The JOE/AVAX market supply state for each market mapping(uint8 => mapping(address => RewardMarketState)) public rewardSupplyState; /// @notice The JOE/AVAX market borrow state for each market mapping(uint8 => mapping(address => RewardMarketState)) public rewardBorrowState; /// @notice The JOE/AVAX borrow index for each market for each supplier as of the last time they accrued reward mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardSupplierIndex; /// @notice The JOE/AVAX borrow index for each market for each borrower as of the last time they accrued reward mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardBorrowerIndex; /// @notice The JOE/AVAX accrued but not yet transferred to each user mapping(uint8 => mapping(address => uint256)) public rewardAccrued; /// @notice The initial reward index for a market uint224 public constant rewardInitialIndex = 1e36; /// @notice JOE token contract address address public joeAddress; } contract RewardDistributor is RewardDistributorStorage, Exponential { /// @notice Emitted when a new reward speed is calculated for a market event RewardSpeedUpdated(uint8 rewardType, JToken indexed jToken, uint256 newSpeed); /// @notice Emitted when JOE/AVAX is distributed to a supplier event DistributedSupplierReward( uint8 rewardType, JToken indexed jToken, address indexed supplier, uint256 rewardDelta, uint256 rewardSupplyIndex ); /// @notice Emitted when JOE/AVAX is distributed to a borrower event DistributedBorrowerReward( uint8 rewardType, JToken indexed jToken, address indexed borrower, uint256 rewardDelta, uint256 rewardBorrowIndex ); /// @notice Emitted when JOE is granted by admin event RewardGranted(uint8 rewardType, address recipient, uint256 amount); bool private initialized; constructor() public { admin = msg.sender; } function initialize() public { require(!initialized, "RewardDistributor already initialized"); joetroller = Joetroller(msg.sender); initialized = true; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == address(joetroller); } /** * @notice Set JOE/AVAX speed for a single market * @param rewardType 0 = QI, 1 = AVAX * @param jToken The market whose reward speed to update * @param rewardSpeed New reward speed for market */ function _setRewardSpeed( uint8 rewardType, JToken jToken, uint256 rewardSpeed ) public { require(rewardType <= 1, "rewardType is invalid"); require(adminOrInitializing(), "only admin can set reward speed"); setRewardSpeedInternal(rewardType, jToken, rewardSpeed); } /** * @notice Set JOE/AVAX speed for a single market * @param rewardType 0: JOE, 1: AVAX * @param jToken The market whose speed to update * @param newSpeed New JOE or AVAX speed for market */ function setRewardSpeedInternal( uint8 rewardType, JToken jToken, uint256 newSpeed ) internal { uint256 currentRewardSpeed = rewardSpeeds[rewardType][address(jToken)]; if (currentRewardSpeed != 0) { // note that JOE speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()}); updateRewardSupplyIndex(rewardType, address(jToken)); updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex); } else if (newSpeed != 0) { // Add the JOE market require(joetroller.isMarketListed(address(jToken)), "reward market is not listed"); if ( rewardSupplyState[rewardType][address(jToken)].index == 0 && rewardSupplyState[rewardType][address(jToken)].timestamp == 0 ) { rewardSupplyState[rewardType][address(jToken)] = RewardMarketState({ index: rewardInitialIndex, timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits") }); } if ( rewardBorrowState[rewardType][address(jToken)].index == 0 && rewardBorrowState[rewardType][address(jToken)].timestamp == 0 ) { rewardBorrowState[rewardType][address(jToken)] = RewardMarketState({ index: rewardInitialIndex, timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits") }); } } if (currentRewardSpeed != newSpeed) { rewardSpeeds[rewardType][address(jToken)] = newSpeed; emit RewardSpeedUpdated(rewardType, jToken, newSpeed); } } /** * @notice Accrue JOE/AVAX to the market by updating the supply index * @param rewardType 0: JOE, 1: AVAX * @param jToken The market whose supply index to update */ function updateRewardSupplyIndex(uint8 rewardType, address jToken) internal { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken]; uint256 supplySpeed = rewardSpeeds[rewardType][jToken]; uint256 blockTimestamp = getBlockTimestamp(); uint256 deltaTimestamps = sub_(blockTimestamp, uint256(supplyState.timestamp)); if (deltaTimestamps > 0 && supplySpeed > 0) { uint256 supplyTokens = JToken(jToken).totalSupply(); uint256 rewardAccrued = mul_(deltaTimestamps, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(rewardAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); rewardSupplyState[rewardType][jToken] = RewardMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits") }); } else if (deltaTimestamps > 0) { supplyState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits"); } } /** * @notice Accrue JOE/AVAX to the market by updating the borrow index * @param rewardType 0: JOE, 1: AVAX * @param jToken The market whose borrow index to update */ function updateRewardBorrowIndex( uint8 rewardType, address jToken, Exp memory marketBorrowIndex ) internal { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken]; uint256 borrowSpeed = rewardSpeeds[rewardType][jToken]; uint256 blockTimestamp = getBlockTimestamp(); uint256 deltaTimestamps = sub_(blockTimestamp, uint256(borrowState.timestamp)); if (deltaTimestamps > 0 && borrowSpeed > 0) { uint256 borrowAmount = div_(JToken(jToken).totalBorrows(), marketBorrowIndex); uint256 rewardAccrued = mul_(deltaTimestamps, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(rewardAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); rewardBorrowState[rewardType][jToken] = RewardMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits") }); } else if (deltaTimestamps > 0) { borrowState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits"); } } /** * @notice Calculate JOE/AVAX accrued by a supplier and possibly transfer it to them * @param rewardType 0: JOE, 1: AVAX * @param jToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute JOE/AVAX to */ function distributeSupplierReward( uint8 rewardType, address jToken, address supplier ) internal { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: rewardSupplierIndex[rewardType][jToken][supplier]}); rewardSupplierIndex[rewardType][jToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = rewardInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = JToken(jToken).balanceOf(supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); uint256 supplierAccrued = add_(rewardAccrued[rewardType][supplier], supplierDelta); rewardAccrued[rewardType][supplier] = supplierAccrued; emit DistributedSupplierReward(rewardType, JToken(jToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate JOE/AVAX accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param rewardType 0: JOE, 1: AVAX * @param jToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute JOE/AVAX to */ function distributeBorrowerReward( uint8 rewardType, address jToken, address borrower, Exp memory marketBorrowIndex ) internal { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: rewardBorrowerIndex[rewardType][jToken][borrower]}); rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta); rewardAccrued[rewardType][borrower] = borrowerAccrued; emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Refactored function to calc and rewards accounts supplier rewards * @param jToken The market to verify the mint against * @param supplier The supplier to be rewarded */ function updateAndDistributeSupplierRewardsForToken(address jToken, address supplier) external { require(adminOrInitializing(), "only admin can update and distribute supplier rewards"); for (uint8 rewardType = 0; rewardType <= 1; rewardType++) { updateRewardSupplyIndex(rewardType, jToken); distributeSupplierReward(rewardType, jToken, supplier); } } /** * @notice Refactored function to calc and rewards accounts supplier rewards * @param jToken The market to verify the mint against * @param borrower Borrower to be rewarded */ function updateAndDistributeBorrowerRewardsForToken( address jToken, address borrower, Exp calldata marketBorrowIndex ) external { require(adminOrInitializing(), "only admin can update and distribute borrower rewards"); for (uint8 rewardType = 0; rewardType <= 1; rewardType++) { updateRewardBorrowIndex(rewardType, jToken, marketBorrowIndex); distributeBorrowerReward(rewardType, jToken, borrower, marketBorrowIndex); } } /*** User functions ***/ /** * @notice Claim all the JOE/AVAX accrued by holder in all markets * @param holder The address to claim JOE/AVAX for */ function claimReward(uint8 rewardType, address payable holder) public { return claimReward(rewardType, holder, joetroller.getAllMarkets()); } /** * @notice Claim all the JOE/AVAX accrued by holder in the specified markets * @param holder The address to claim JOE/AVAX for * @param jTokens The list of markets to claim JOE/AVAX in */ function claimReward( uint8 rewardType, address payable holder, JToken[] memory jTokens ) public { address payable[] memory holders = new address payable[](1); holders[0] = holder; claimReward(rewardType, holders, jTokens, true, true); } /** * @notice Claim all JOE/AVAX accrued by the holders * @param rewardType 0 = JOE, 1 = AVAX * @param holders The addresses to claim JOE/AVAX for * @param jTokens The list of markets to claim JOE/AVAX in * @param borrowers Whether or not to claim JOE/AVAX earned by borrowing * @param suppliers Whether or not to claim JOE/AVAX earned by supplying */ function claimReward( uint8 rewardType, address payable[] memory holders, JToken[] memory jTokens, bool borrowers, bool suppliers ) public payable { require(rewardType <= 1, "rewardType is invalid"); for (uint256 i = 0; i < jTokens.length; i++) { JToken jToken = jTokens[i]; require(joetroller.isMarketListed(address(jToken)), "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()}); updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex); for (uint256 j = 0; j < holders.length; j++) { distributeBorrowerReward(rewardType, address(jToken), holders[j], borrowIndex); rewardAccrued[rewardType][holders[j]] = grantRewardInternal( rewardType, holders[j], rewardAccrued[rewardType][holders[j]] ); } } if (suppliers == true) { updateRewardSupplyIndex(rewardType, address(jToken)); for (uint256 j = 0; j < holders.length; j++) { distributeSupplierReward(rewardType, address(jToken), holders[j]); rewardAccrued[rewardType][holders[j]] = grantRewardInternal( rewardType, holders[j], rewardAccrued[rewardType][holders[j]] ); } } } } /** * @notice Transfer JOE/AVAX to the user * @dev Note: If there is not enough JOE/AVAX, we do not perform the transfer all. * @param user The address of the user to transfer JOE/AVAX to * @param amount The amount of JOE/AVAX to (possibly) transfer * @return The amount of JOE/AVAX which was NOT transferred to the user */ function grantRewardInternal( uint256 rewardType, address payable user, uint256 amount ) internal returns (uint256) { if (rewardType == 0) { EIP20Interface joe = EIP20Interface(joeAddress); uint256 joeRemaining = joe.balanceOf(address(this)); if (amount > 0 && amount <= joeRemaining) { joe.transfer(user, amount); return 0; } } else if (rewardType == 1) { uint256 avaxRemaining = address(this).balance; if (amount > 0 && amount <= avaxRemaining) { user.transfer(amount); return 0; } } return amount; } /*** Joe Distribution Admin ***/ /** * @notice Transfer JOE to the recipient * @dev Note: If there is not enough JOE, we do not perform the transfer all. * @param recipient The address of the recipient to transfer JOE to * @param amount The amount of JOE to (possibly) transfer */ function _grantReward( uint8 rewardType, address payable recipient, uint256 amount ) public { require(adminOrInitializing(), "only admin can grant joe"); uint256 amountLeft = grantRewardInternal(rewardType, recipient, amount); require(amountLeft == 0, "insufficient joe for grant"); emit RewardGranted(rewardType, recipient, amount); } /** * @notice Set the JOE token address */ function setJoeAddress(address newJoeAddress) public { require(msg.sender == admin, "only admin can set JOE"); joeAddress = newJoeAddress; } /** * @notice Set the Joetroller address */ function setJoetroller(address _joetroller) public { require(msg.sender == admin, "only admin can set Joetroller"); joetroller = Joetroller(_joetroller); } /** * @notice Set the admin */ function setAdmin(address _newAdmin) public { require(msg.sender == admin, "only admin can set admin"); admin = _newAdmin; } /** * @notice payable function needed to receive AVAX */ function() external payable {} function getBlockTimestamp() public view returns (uint256) { return block.timestamp; } } /** * @title JoetrollerCore * @dev Storage for the joetroller is at this address, while execution is delegated to the `joetrollerImplementation`. * JTokens should reference this contract as their joetroller. */ contract Unitroller is UnitrollerAdminStorage, JoetrollerErrorReporter { /** * @notice Emitted when pendingJoetrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingJoetrollerImplementation is accepted, which means joetroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingJoetrollerImplementation; pendingJoetrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Accepts new implementation of joetroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint256) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingJoetrollerImplementation || pendingJoetrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = joetrollerImplementation; address oldPendingImplementation = pendingJoetrollerImplementation; joetrollerImplementation = pendingJoetrollerImplementation; pendingJoetrollerImplementation = address(0); emit NewImplementation(oldImplementation, joetrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller is pendingAdmin if (msg.sender != pendingAdmin) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function() external payable { // delegate all other functions to current implementation (bool success, ) = joetrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } /** * @title Compound's Joetroller Contract * @author Compound (modified by Cream) */ contract Joetroller is JoetrollerV1Storage, JoetrollerInterface, JoetrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(JToken jToken); /// @notice Emitted when an admin delists a market event MarketDelisted(JToken jToken); /// @notice Emitted when an account enters a market event MarketEntered(JToken jToken, address account); /// @notice Emitted when an account exits a market event MarketExited(JToken jToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(JToken jToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle 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(JToken jToken, string action, bool pauseState); /// @notice Emitted when borrow cap for a jToken is changed event NewBorrowCap(JToken indexed jToken, uint256 newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when supply cap for a jToken is changed event NewSupplyCap(JToken indexed jToken, uint256 newSupplyCap); /// @notice Emitted when supply cap guardian is changed event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian); /// @notice Emitted when protocol's credit limit has changed event CreditLimitChanged(address protocol, uint256 creditLimit); /// @notice Emitted when jToken version is changed event NewJTokenVersion(JToken jToken, Version oldVersion, Version newVersion); // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() public { admin = msg.sender; } /** * @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 (JToken[] memory) { return allMarkets; } function getBlockTimestamp() public view returns (uint256) { return block.timestamp; } /*** 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 (JToken[] memory) { JToken[] 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 jToken The jToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, JToken jToken) external view returns (bool) { return markets[address(jToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param jTokens The list of addresses of the jToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory jTokens) public returns (uint256[] memory) { uint256 len = jTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { JToken jToken = JToken(jTokens[i]); results[i] = uint256(addToMarketInternal(jToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param jToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(JToken jToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(jToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.version == Version.COLLATERALCAP) { // register collateral for the borrower if the token is CollateralCap version. JCollateralCapErc20Interface(address(jToken)).registerCollateral(borrower); } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(jToken); emit MarketEntered(jToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param jTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address jTokenAddress) external returns (uint256) { JToken jToken = JToken(jTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the jToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = jToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint256 allowed = redeemAllowedInternal(jTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[jTokenAddress]; if (marketToExit.version == Version.COLLATERALCAP) { JCollateralCapErc20Interface(jTokenAddress).unregisterCollateral(msg.sender); } /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set jToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete jToken from the account’s list of assets */ // load into memory for faster iteration JToken[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == jToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 JToken[] storage storedList = accountAssets[msg.sender]; if (assetIndex != storedList.length - 1) { storedList[assetIndex] = storedList[storedList.length - 1]; } storedList.length--; emit MarketExited(jToken, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice Return whether a specific market is listed or not * @param jTokenAddress The address of the asset to be checked * @return Whether or not the market is listed */ function isMarketListed(address jTokenAddress) public view returns (bool) { return markets[jTokenAddress].isListed; } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param jToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address jToken, address minter, uint256 mintAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[jToken], "mint is paused"); require(!isCreditAccount(minter), "credit account cannot mint"); if (!isMarketListed(jToken)) { return uint256(Error.MARKET_NOT_LISTED); } uint256 supplyCap = supplyCaps[jToken]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0) { uint256 totalCash = JToken(jToken).getCash(); uint256 totalBorrows = JToken(jToken).totalBorrows(); uint256 totalReserves = JToken(jToken).totalReserves(); // totalSupplies = totalCash + totalBorrows - totalReserves (MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves); require(mathErr == MathError.NO_ERROR, "totalSupplies failed"); uint256 nextTotalSupplies = add_(totalSupplies, mintAmount); require(nextTotalSupplies < supplyCap, "market supply cap reached"); } // Keep the flywheel moving RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, minter); return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param jToken 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 jToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Shh - currently unused jToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param jToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of jTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address jToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { uint256 allowed = redeemAllowedInternal(jToken, redeemer, redeemTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } // Keep the flywheel going RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, redeemer); return uint256(Error.NO_ERROR); } function redeemAllowedInternal( address jToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!isMarketListed(jToken)) { return uint256(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[jToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, JToken(jToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param jToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address jToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { // Shh - currently unused jToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param jToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address jToken, address borrower, uint256 borrowAmount ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[jToken], "borrow is paused"); if (!isMarketListed(jToken)) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[jToken].accountMembership[borrower]) { // only jTokens may call borrowAllowed if borrower not in market require(msg.sender == jToken, "sender must be jToken"); // attempt to add borrower to the market Error err = addToMarketInternal(JToken(jToken), borrower); if (err != Error.NO_ERROR) { return uint256(err); } // it should be impossible to break the important invariant assert(markets[jToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(JToken(jToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[jToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint256 totalBorrows = JToken(jToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, JToken(jToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel going Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()}); RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex); return uint256(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param jToken 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 jToken, address borrower, uint256 borrowAmount ) external { // Shh - currently unused jToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param jToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address jToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { // Shh - currently unused payer; borrower; repayAmount; if (!isMarketListed(jToken)) { return uint256(Error.MARKET_NOT_LISTED); } // Keep the flywheel going Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()}); RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex); return uint256(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param jToken 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 jToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { // Shh - currently unused jToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the liquidation should be allowed to occur * @param jTokenBorrowed Asset which was borrowed by the borrower * @param jTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address jTokenBorrowed, address jTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { require(!isCreditAccount(borrower), "cannot liquidate credit account"); // Shh - currently unused liquidator; if (!isMarketListed(jTokenBorrowed) || !isMarketListed(jTokenCollateral)) { return uint256(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = JToken(jTokenBorrowed).borrowBalanceStored(borrower); uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } return uint256(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param jTokenBorrowed Asset which was borrowed by the borrower * @param jTokenCollateral 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 jTokenBorrowed, address jTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { // Shh - currently unused jTokenBorrowed; jTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param jTokenCollateral Asset which was used as collateral and will be seized * @param jTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address jTokenCollateral, address jTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); require(!isCreditAccount(borrower), "cannot sieze from credit account"); // Shh - currently unused liquidator; seizeTokens; if (!isMarketListed(jTokenCollateral) || !isMarketListed(jTokenBorrowed)) { return uint256(Error.MARKET_NOT_LISTED); } if (JToken(jTokenCollateral).joetroller() != JToken(jTokenBorrowed).joetroller()) { return uint256(Error.JOETROLLER_MISMATCH); } // Keep the flywheel moving RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, borrower); RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, liquidator); return uint256(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param jTokenCollateral Asset which was used as collateral and will be seized * @param jTokenBorrowed 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 jTokenCollateral, address jTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { // Shh - currently unused jTokenCollateral; jTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param jToken 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 jTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address jToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); require(!isCreditAccount(dst), "cannot transfer to a credit account"); // Shh - currently unused dst; // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint256 allowed = redeemAllowedInternal(jToken, src, transferTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, src); RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, dst); return uint256(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param jToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of jTokens to transfer */ function transferVerify( address jToken, address src, address dst, uint256 transferTokens ) external { // Shh - currently unused jToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { closeFactorMantissa = closeFactorMantissa; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param jToken The market to verify the transfer against * @param receiver The account which receives the tokens * @param amount The amount of the tokens * @param params The other parameters */ function flashloanAllowed( address jToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool) { return !flashloanGuardianPaused[jToken]; } /** * @notice Update JToken's version. * @param jToken Version of the asset being updated * @param newVersion The new version */ function updateJTokenVersion(address jToken, Version newVersion) external { require(msg.sender == jToken, "only jToken could update its version"); // This function will be called when a new JToken implementation becomes active. // If a new JToken is newly created, this market is not listed yet. The version of // this market will be taken care of when calling `_supportMarket`. if (isMarketListed(jToken)) { Version oldVersion = markets[jToken].version; markets[jToken].version = newVersion; emit NewJTokenVersion(JToken(jToken), oldVersion, newVersion); } } /** * @notice Check if the account is a credit account * @param account The account needs to be checked * @return The account is a credit account or not */ function isCreditAccount(address account) public view returns (bool) { return creditLimits[account] > 0; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `jTokenBalance` is the number of jTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 jTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, JToken(0), 0, 0 ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, JToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param jTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address jTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { (Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, JToken(jTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param jTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral jToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, JToken jTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { // If credit limit is set to MAX, no need to check account liquidity. if (creditLimits[account] == uint256(-1)) { return (Error.NO_ERROR, uint256(-1), 0); } AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint256 oErr; // For each asset the account is in JToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { JToken asset = assets[i]; // Read the balances and exchange rate from the jToken (oErr, vars.jTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot( account ); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } // Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. // If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. if (vars.jTokenBalance == 0 && vars.borrowBalance == 0 && asset != jTokenModify) { continue; } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * jTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.jTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with jTokenModify if (asset == jTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } // If credit limit is set, no need to consider collateral. if (creditLimits[account] > 0) { vars.sumCollateral = creditLimits[account]; } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in jToken.liquidateBorrowFresh) * @param jTokenBorrowed The address of the borrowed jToken * @param jTokenCollateral The address of the collateral jToken * @param actualRepayAmount The amount of jTokenBorrowed underlying to convert into jTokenCollateral tokens * @return (errorCode, number of jTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address jTokenBorrowed, address jTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(JToken(jTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(JToken(jTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint256(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint256 exchangeRateMantissa = JToken(jTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) { if (msg.sender != admin) { return uint256(Error.UNAUTHORIZED); } (bool success, ) = newRewardDistributor.call.value(0)(abi.encodeWithSignature("initialize()", 0)); if (!success) { return uint256(Error.REJECTION); } address oldRewardDistributor = rewardDistributor; rewardDistributor = newRewardDistributor; return uint256(Error.NO_ERROR); } /** * @notice Sets a new price oracle for the joetroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the joetroller PriceOracle oldOracle = oracle; // Set joetroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param jToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(JToken jToken, uint256 newCollateralFactorMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(jToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(jToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(jToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param jToken The address of the market (token) to list * @param version The version of the market (token) * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(JToken jToken, Version version) external returns (uint256) { require(msg.sender == admin, "only admin may support market"); require(!isMarketListed(address(jToken)), "market already listed"); jToken.isJToken(); // Sanity check to make sure its really a JToken markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version}); _addMarketInternal(address(jToken)); emit MarketListed(jToken); return uint256(Error.NO_ERROR); } /** * @notice Remove the market from the markets mapping * @param jToken The address of the market (token) to delist */ function _delistMarket(JToken jToken) external { require(msg.sender == admin, "only admin may delist market"); require(isMarketListed(address(jToken)), "market not listed"); require(jToken.totalSupply() == 0, "market not empty"); jToken.isJToken(); // Sanity check to make sure its really a JToken delete markets[address(jToken)]; for (uint256 i = 0; i < allMarkets.length; i++) { if (allMarkets[i] == jToken) { allMarkets[i] = allMarkets[allMarkets.length - 1]; delete allMarkets[allMarkets.length - 1]; allMarkets.length--; break; } } emit MarketDelisted(jToken); } function _addMarketInternal(address jToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != JToken(jToken), "market already added"); } allMarkets.push(JToken(jToken)); } /** * @notice Admin function to change the Supply Cap Guardian * @param newSupplyCapGuardian The address of the new Supply Cap Guardian */ function _setSupplyCapGuardian(address newSupplyCapGuardian) external { require(msg.sender == admin, "only admin can set supply cap guardian"); // Save current value for inclusion in log address oldSupplyCapGuardian = supplyCapGuardian; // Store supplyCapGuardian with value newSupplyCapGuardian supplyCapGuardian = newSupplyCapGuardian; // Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian) emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian); } /** * @notice Set the given supply caps for the given jToken markets. Supplying that brings total supplys to or above supply cap will revert. * @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows * already exceeded the cap, it will prevent anyone to borrow. * @param jTokens 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(JToken[] calldata jTokens, uint256[] calldata newSupplyCaps) external { require( msg.sender == admin || msg.sender == supplyCapGuardian, "only admin or supply cap guardian can set supply caps" ); uint256 numMarkets = jTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(jTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(jTokens[i], newSupplyCaps[i]); } } /** * @notice Set the given borrow caps for the given jToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies * already exceeded the cap, it will prevent anyone to mint. * @param jTokens 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(JToken[] calldata jTokens, uint256[] calldata newBorrowCaps) external { require( msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps" ); uint256 numMarkets = jTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(jTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(jTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint256(Error.NO_ERROR); } function _setMintPaused(JToken jToken, bool state) public returns (bool) { require(isMarketListed(address(jToken)), "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(jToken)] = state; emit ActionPaused(jToken, "Mint", state); return state; } function _setBorrowPaused(JToken jToken, bool state) public returns (bool) { require(isMarketListed(address(jToken)), "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(jToken)] = state; emit ActionPaused(jToken, "Borrow", state); return state; } function _setFlashloanPaused(JToken jToken, bool state) public returns (bool) { require(isMarketListed(address(jToken)), "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); flashloanGuardianPaused[address(jToken)] = state; emit ActionPaused(jToken, "Flashloan", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Sets whitelisted protocol's credit limit * @param protocol The address of the protocol * @param creditLimit The credit limit */ function _setCreditLimit(address protocol, uint256 creditLimit) public { require(msg.sender == admin, "only admin can set protocol credit limit"); creditLimits[protocol] = creditLimit; emit CreditLimitChanged(protocol, creditLimit); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == joetrollerImplementation; } /*** Reward distribution functions ***/ /** * @notice Claim all the JOE/AVAX accrued by holder in all markets * @param holder The address to claim JOE/AVAX for */ function claimReward(uint8 rewardType, address payable holder) public { RewardDistributor(rewardDistributor).claimReward(rewardType, holder); } /** * @notice Claim all the JOE/AVAX accrued by holder in the specified markets * @param holder The address to claim JOE/AVAX for * @param jTokens The list of markets to claim JOE/AVAX in */ function claimReward( uint8 rewardType, address payable holder, JToken[] memory jTokens ) public { RewardDistributor(rewardDistributor).claimReward(rewardType, holder, jTokens); } /** * @notice Claim all JOE/AVAX accrued by the holders * @param rewardType 0 = JOE, 1 = AVAX * @param holders The addresses to claim JOE/AVAX for * @param jTokens The list of markets to claim JOE/AVAX in * @param borrowers Whether or not to claim JOE/AVAX earned by borrowing * @param suppliers Whether or not to claim JOE/AVAX earned by supplying */ function claimReward( uint8 rewardType, address payable[] memory holders, JToken[] memory jTokens, bool borrowers, bool suppliers ) public payable { RewardDistributor(rewardDistributor).claimReward(rewardType, holders, jTokens, borrowers, suppliers); } }
Sender redeems jTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of jTokens to redeem into underlying isNative The amount is in native or not return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } }
1,810,022
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.5.16; //Safe Math Interface contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b);} function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } //Token Contract contract EdToken is SafeMath { //to store the balance of each address mapping(address => uint256) private _balances; //to store the amount allows to be withdrawn from one account by another mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; //total supply of tokens uint256 private _priceOfToken; //price of one token in ether string private _name; // name of the token string private _symbol; // symbol of the token address public _deployer; // deployer of the token gets access to mint new tokens event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor(string memory name_, string memory symbol_, uint256 totalSupply_, uint256 priceOfToken_) public { _name = name_; _symbol = symbol_; _totalSupply = totalSupply_; _priceOfToken = priceOfToken_; // deduct 1000 tokens from total token supply _totalSupply=safeSub(_totalSupply,1000); // unchecked{ // _totalSupply -= 1000; // } // assigning 1000 tokens to the contract owner _balances[msg.sender] = 1000; _deployer = msg.sender; } // returns the name of the token function name() public view returns (string memory) { return _name; } // returns the symbol of the token function symbol() public view returns (string memory) { return _symbol; } // returns the number of decimals accepted in the token value function decimals() public pure returns (uint8) { return 0; } // returns the total supply of the tokens function totalSupply() public view returns (uint256) { return _totalSupply; } // returns the balance of the specified account function balanceOf(address account) public view returns (uint256) { return _balances[account]; } // function to transfer amount number of tokens from the caller to the recipient function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // returns the amount of the tokens spender can spend from the owner's account function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } // function to approve amount number of tokens to be spend by the spender from the caller's account function approve(address spender, uint256 amount) public returns (bool) { _approve(msg.sender,spender,amount); return true; } // function to transfer amount number of tokens from the sender's account to recipient's account function transferFrom(address sender,address recipient,uint256 amount) public returns (bool) { // uint256 currentAllowance = _allowances[sender][recipient]; // require(currentAllowance >= amount, "EdToken: transfer amount exceeds allowance "); _transfer(sender, recipient, amount); // uint256 approvAmt = safeSub(currentAllowance,amount); // _approve(sender, recipient, approvAmt); // unchecked { // _approve(sender, recipient, currentAllowance - amount); // } return true; } // function to mint new tokens function mint(uint256 amount) public returns (uint256) { require(msg.sender == _deployer, "EdToken: only the owner can mint new tokens."); _totalSupply += amount; return _totalSupply; } // function to burn the tokens from a specific account to create inflation function burn(uint256 amount) public returns (uint256) { address account = msg.sender; require(account != address(0), "EdToken: burn from the zero address"); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "EdToken: burn amount exceeds balance"); _balances[account] = safeSub(accountBalance,amount); // unchecked { // _balances[account] = accountBalance - amount; // } _totalSupply -= amount; emit Transfer(account, address(0), amount); return _balances[account]; } // function to buy new tokens by spending ether function buy(uint256 amount) payable public returns (bool){ require(msg.value == amount*_priceOfToken , "EdToken: Insufficient or Excess supply of funds"); require(_totalSupply >= amount,"EdToken: Available tokens less than the required amount"); _balances[msg.sender] += amount; _totalSupply=safeSub(_totalSupply,amount); emit Transfer(msg.sender, address(this), amount); return true; } // function to sell the tokens and transfer ether back to the owner function sell(uint256 amount,address payable owner) public returns (bool){ require(_balances[msg.sender] >= amount , "EdToken: Insufficient token balance"); require(address(this).balance >= amount*_priceOfToken,"EdToken: Insufficient funds in the contract"); owner.transfer(amount*_priceOfToken); _totalSupply += amount; _balances[msg.sender] =safeSub(_balances[msg.sender],amount); emit Transfer(address(this), msg.sender, amount); return true; } // returns the total balance of the contract account in terms of ether function getContractBalance() public view returns(uint256){ return address(this).balance; } // function to transfer amount number of tokens from sender to the recipient function _transfer(address sender,address recipient,uint256 amount) internal { require(sender != address(0), "EdToken: transfer from the zero address"); require(recipient != address(0), "EdToken: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "EdToken: transfer amount exceeds balance"); _balances[sender]=safeSub(senderBalance,amount); _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } // function to approve spender to spend amount number of tokens from the owner's account function _approve(address owner,address spender,uint256 amount) internal{ require(owner != address(0), "EdToken: approve from the zero address"); require(spender != address(0), "EdToken: approve to the zero address"); require(_balances[owner] >= amount, "EdToken: approve amount less than the current balance"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
function to approve amount number of tokens to be spend by the spender from the caller's account
function approve(address spender, uint256 amount) public returns (bool) { _approve(msg.sender,spender,amount); return true; }
984,314
./full_match/43114/0x2115f83922Ad1D732bbd3b3A255f861d6B95079F/sources/project_/contracts/libs/SafeMath16.sol
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(uint16 a, uint16 b) internal pure returns (uint16) { require(b > 0, "SafeMath: division by zero"); return a / b; }
4,600,345
// Created using Token Wizard https://github.com/poanetwork/token-wizard by POA Network pragma solidity ^0.4.11; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // Temporarily have SafeMath here until all contracts have been migrated to SafeMathLib version from OpenZeppelin /** * Math operations with safety checks */ contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMath { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don&#39;t have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { // Called in a bad state throw; } // Validate input value. if (value == 0) throw; balances[msg.sender] = safeSub(balances[msg.sender], value); // Take tokens out from circulation totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading throw; } if (agent == 0x0) throw; // Only a master can designate the next agent if (msg.sender != upgradeMaster) throw; // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) throw; upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) throw; // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) throw; UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns(bool) { return true; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is ERC20, Ownable { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { if(!released) { if(!transferAgents[_sender]) { throw; } } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don&#39;t do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { if(releaseState != released) { throw; } _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { throw; } _; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLibExt { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function divides(uint a, uint b) returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableTokenExt is StandardToken, Ownable { using SafeMathLibExt for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** inPercentageUnit is percents of tokens multiplied to 10 up to percents decimals. * For example, for reserved tokens in percents 2.54% * inPercentageUnit = 254 * inPercentageDecimals = 2 */ struct ReservedTokensData { uint inTokens; uint inPercentageUnit; uint inPercentageDecimals; bool isReserved; bool isDistributed; } mapping (address => ReservedTokensData) public reservedTokensList; address[] public reservedTokensDestinations; uint public reservedTokensDestinationsLen = 0; bool reservedTokensDestinationsAreSet = false; modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if(!mintAgents[msg.sender]) { throw; } _; } /** Make sure we are not done yet. */ modifier canMint() { if(mintingFinished) throw; _; } function finalizeReservedAddress(address addr) public onlyMintAgent canMint { ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; reservedTokensData.isDistributed = true; } function isAddressReserved(address addr) public constant returns (bool isReserved) { return reservedTokensList[addr].isReserved; } function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) { return reservedTokensList[addr].isDistributed; } function getReservedTokens(address addr) public constant returns (uint inTokens) { return reservedTokensList[addr].inTokens; } function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) { return reservedTokensList[addr].inPercentageUnit; } function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) { return reservedTokensList[addr].inPercentageDecimals; } function setReservedTokensListMultiple( address[] addrs, uint[] inTokens, uint[] inPercentageUnit, uint[] inPercentageDecimals ) public canMint onlyOwner { assert(!reservedTokensDestinationsAreSet); assert(addrs.length == inTokens.length); assert(inTokens.length == inPercentageUnit.length); assert(inPercentageUnit.length == inPercentageDecimals.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { if (addrs[iterator] != address(0)) { setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]); } } reservedTokensDestinationsAreSet = true; } /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner { assert(addr != address(0)); if (!isAddressReserved(addr)) { reservedTokensDestinations.push(addr); reservedTokensDestinationsLen++; } reservedTokensList[addr] = ReservedTokensData({ inTokens: inTokens, inPercentageUnit: inPercentageUnit, inPercentageDecimals: inPercentageDecimals, isReserved: true, isDistributed: false }); } } /** * A crowdsaled token. * * An ERC-20 token designed specifically for crowdsales with investor protection and further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through approve() mechanism * - The token can be capped (supply set in the constructor) or uncapped (crowdsale contract can mint new tokens) * */ contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken { /** Name and symbol were updated. */ event UpdatedTokenInformation(string newName, string newSymbol); event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); string public name; string public symbol; uint public decimals; /* Minimum ammount of tokens every buyer can buy. */ uint public minCap; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places * @param _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends. */ function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap) UpgradeableToken(msg.sender) { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply = _initialSupply; decimals = _decimals; minCap = _globalMinCap; // Create initially all balance on the team multisig balances[owner] = totalSupply; if(totalSupply > 0) { Minted(owner, totalSupply); } // No more new supply allowed after the token creation if(!_mintable) { mintingFinished = true; if(totalSupply == 0) { throw; // Cannot create a token without supply and no minting } } } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyReleaseAgent { mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public constant returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function setTokenInformation(string _name, string _symbol) onlyOwner { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } /** * Claim tokens that were accidentally sent to this contract. * * @param _token The address of the token contract that you want to recover. */ function claimTokens(address _token) public onlyOwner { require(_token != address(0)); ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); } }
Create new tokens and allocate them to an address.. Only callably by a crowdsale contract (mint agent)./ This will make the mint transaction apper in EtherScan.io We can remove this after there is a standardized minting event
function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); Transfer(0, receiver, amount); }
1,979,598
/** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLib { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** @title ERC827 interface, an extension of ERC20 token standard Interface of a ERC827 token, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. */ contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } /** @title ERC827, an extension of ERC20 token standard Implementation the ERC827, following the ERC20 standard with extra methods to transfer value and data and execute calls in transfers and approvals. Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. 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 that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Recoverable is Ownable { /// @dev Empty constructor (for now) function Recoverable() { } /// @dev This will be invoked by the owner, when owner wants to rescue tokens /// @param token Token which will we rescue to the owner from the contract function recoverTokens(ERC20Basic token) onlyOwner public { token.transfer(owner, tokensToBeReturned(token)); } /// @dev Interface function, can be overwritten by the superclass /// @param token Token which balance we will check and return /// @return The amount of tokens (in smallest denominator) the contract owns function tokensToBeReturned(ERC20Basic token) public returns (uint) { return token.balanceOf(this); } } /** * Standard EIP-20 token with an interface marker. * * @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract. * */ contract StandardTokenExt is StandardToken, ERC827Token, Recoverable { /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } } /** * Hold tokens for a group investor of investors until the unlock date. * * After the unlock date the investor can claim their tokens. * * Steps * * - Deploy this contract * - Move tokensToBeAllocated to this contract using StandardToken.transfer() * - Call setInvestor for all investors from the owner account using a local script and CSV input * - Wait until the freeze period is over * - After the freeze time is over investors can call claim() from their address to get their tokens * */ contract InvestorTimeVault is Ownable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When our claim freeze is over (UNIX timestamp) */ mapping(address => uint) public freezeEndsAt; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); /** * Create contract for presale investors where tokens will be locked for a period of time * * @param _owner Who can load investor data and lock * @param _token Token contract address we are distributing * */ function InvestorTimeVault(address _owner, address _token) { owner = _owner; // Invalid owenr if(owner == 0) { throw; } token = StandardTokenExt(_token); // Check the address looks like a token contract if(!token.isToken()) { throw; } } /// @dev Add a presale participating allocation function setInvestor(address investor, uint _freezeEndsAt, uint amount) public onlyOwner { uint tokensTotal = (token.balanceOf(address(this))).plus(totalClaimed); uint unallocatedTokens = tokensTotal.minus(tokensAllocatedTotal); // Tokens we have in vault with no owner set if(amount == 0) throw; // No empty buys if(amount > unallocatedTokens) throw; // Can not lock tokens the vault don't have if(now > _freezeEndsAt) throw; // Trying to lock for negative period of time // Don't allow reset if(balances[investor] > 0) { throw; } balances[investor] = amount; freezeEndsAt[investor] = _freezeEndsAt; investorCount++; tokensAllocatedTotal = tokensAllocatedTotal.plus(amount); Allocated(investor, amount); } /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(balances[investor] == 0) { // Not our investor throw; } if(now < freezeEndsAt[investor]) { throw; // Trying to claim early } uint amount = balances[investor]; balances[investor] = 0; claimed[investor] = claimed[investor].plus(amount); totalClaimed = totalClaimed.plus(amount); token.transfer(investor, amount); Distributed(investor, amount); } }
Get the current balance of tokens in the vault return uint How many tokens there are currently in vault
function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); }
5,521,584
./partial_match/42/0x579AbEEE14a52A4CA6707a4590c524Dc149D56a1/sources/CompoundLeverageModule.sol
Calculates protocol fee on module land pays protocol fee from SetToken/
function _accrueProtocolFee(ISetToken _setToken, address _receiveToken, uint256 _exchangedQuantity) internal returns(uint256) { uint256 protocolFeeTotal = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity); payProtocolFeeFromSetToken(_setToken, _receiveToken, protocolFeeTotal); return protocolFeeTotal; }
3,334,041
./partial_match/97/0x700b57582d08620966adb67396D6723Fa38b0370/sources/UNOVA.sol
Checks whether the given pool(_pid) already exists
function checkPoolDuplicate(IBEP20 _lpToken) public view { uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; _pid++) { require(poolInfo[_pid].lpToken != _lpToken, "Existing:Pool"); } }
11,449,939
pragma solidity ^0.4.23; import "./CutieERC721Metadata.sol"; import "./ERC721TokenReceiver.sol"; import "./TokenRecipientInterface.sol"; contract BlockchainCutiesToken is CutieERC721Metadata { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); // @dev This struct represents a blockchain Cutie. It was ensured that struct fits well into // exactly two 256-bit words. The order of the members in this structure // matters because of the Ethereum byte-packing rules.CutieERC721Metadata // Reference: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Cutie { // The Cutie's genetic code is in these 256-bits. Cutie's genes never change. uint256 genes; // The timestamp from the block when this cutie was created. uint40 birthTime; // The minimum timestamp after which the cutie can start breeding // again. uint40 cooldownEndTime; // The cutie's parents ID is set to 0 for gen0 cuties. uint40 momId; uint40 dadId; // Set the index in the cooldown array (see below) that means // the current cooldown duration for this Cutie. Starts at 0 // for gen0 cats, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding, regardless // of being cutie mom or cutie dad. uint16 cooldownIndex; // The "generation number" of the cutie. Cuties minted by the contract // for sale are called "gen0" with generation number of 0. All other cuties' // generation number is the larger of their parents' two generation // numbers, plus one (i.e. max(mom.generation, dad.generation) + 1) uint16 generation; // Some optional data used by external contracts // Cutie struct is 2x256 bits long. uint64 optional; } bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('tokenURI(uint256)')); bytes4 internal constant INTERFACE_SIGNATURE_ERC721Enumerable = bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('tokenByIndex(uint256)')) ^ bytes4(keccak256('tokenOfOwnerByIndex(address, uint256)')); // @dev An mapping containing the Cutie struct for all Cuties in existence. // The ID of each cutie is actually an index into this mapping. // ID 0 is the parent of all generation 0 cats, and both parents to itself. It is an invalid genetic code. mapping (uint40 => Cutie) public cuties; // @dev Total cuties count uint256 total; // @dev Core game contract address address public gameAddress; // @dev A mapping from cutie IDs to the address that owns them. All cuties have // some valid owner address, even gen0 cuties are created with a non-zero owner. mapping (uint40 => address) public cutieIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; // @dev A mapping from CutieIDs to an address that has been approved to call // transferFrom(). A Cutie can have one approved address for transfer // at any time. A zero value means that there is no outstanding approval. mapping (uint40 => address) public cutieIndexToApproved; // @dev A mapping from Cuties owner (account) to an address that has been approved to call // transferFrom() for all cuties, owned by owner. // Only one approved address is permitted for each account for transfer // at any time. A zero value means there is no outstanding approval. mapping (address => mapping (address => bool)) public addressToApprovedAll; // Modifiers to check that inputs can be safely stored with a certain number of bits modifier canBeStoredIn40Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFF, "Value can't be stored in 40 bits"); _; } modifier onlyGame { require(msg.sender == gameAddress || msg.sender == ownerAddress, "Access denied"); _; } constructor() public { // Starts paused. paused = true; } // @dev Accept all Ether function() external payable {} function setup(uint256 _total) external onlyGame whenPaused { require(total == 0, "Contract already initialized"); total = _total; paused = false; } function setGame(address _gameAddress) external onlyOwner { gameAddress = _gameAddress; } // @notice Query if a contract implements an interface // @param interfaceID The interface identifier, as specified in ERC-165 // @dev Interface identification is specified in ERC-165. This function // uses less than 30,000 gas. // @return `true` if the contract implements `interfaceID` and // `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external pure returns (bool) { return interfaceID == 0x6466353c || interfaceID == 0x80ac58cd || // ERC721 interfaceID == INTERFACE_SIGNATURE_ERC721Metadata || interfaceID == INTERFACE_SIGNATURE_ERC721Enumerable || interfaceID == bytes4(keccak256('supportsInterface(bytes4)')); } // @notice Returns the total number of Cuties in existence. // @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return total; } // @notice Returns the number of Cuties owned by a specific address. // @param _owner The owner address to check. // @dev Required for ERC-721 compliance function balanceOf(address _owner) external view returns (uint256) { require(_owner != 0x0, "Owner can't be zero address"); return ownershipTokenCount[_owner]; } // @notice Returns the address currently assigned ownership of a given Cutie. // @dev Required for ERC-721 compliance. function ownerOf(uint256 _cutieId) external view canBeStoredIn40Bits(_cutieId) returns (address owner) { owner = cutieIndexToOwner[uint40(_cutieId)]; require(owner != address(0), "Owner query for nonexistent token"); } // @notice Returns the address currently assigned ownership of a given Cutie. // @dev do not revert when cutie has no owner function ownerOfCutie(uint256 _cutieId) external view canBeStoredIn40Bits(_cutieId) returns (address) { return cutieIndexToOwner[uint40(_cutieId)]; } // @notice Enumerate valid NFTs // @dev Throws if `_index` >= `totalSupply()`. // @param _index A counter less than `totalSupply()` // @return The token identifier for the `_index`th NFT, // (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < total); return _index - 1; } // @notice Returns the nth Cutie assigned to an address, with n specified by the // _index argument. // @param _owner The owner of the Cuties we are interested in. // @param _index The zero-based index of the cutie within the owner's list of cuties. // Must be less than balanceOf(_owner). // @dev This method must not be called by smart contract code. It will almost // certainly blow past the block gas limit once there are a large number of // Cuties in existence. Exists only to allow off-chain queries of ownership. // Optional method for ERC-721. function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 cutieId) { require(_owner != 0x0, "Owner can't be 0x0"); uint40 count = 0; for (uint40 i = 1; i <= totalSupply(); ++i) { if (_isOwner(_owner, i)) { if (count == _index) { return i; } else { count++; } } } revert(); } // @notice Transfers the ownership of an NFT from one address to another address. // @dev Throws unless `msg.sender` is the current owner, an authorized // operator, or the approved address for this NFT. Throws if `_from` is // not the current owner. Throws if `_to` is the zero address. Throws if // `_tokenId` is not a valid NFT. When transfer is complete, this function // checks if `_to` is a smart contract (code size > 0). If so, it calls // `onERC721Received` on `_to` and throws if the return value is not // `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. // @param _from The current owner of the NFT // @param _to The new owner // @param _tokenId The NFT to transfer // @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public whenNotPaused canBeStoredIn40Bits(_tokenId) { transferFrom(_from, _to, uint40(_tokenId)); if (_isContract(_to)) { ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); } } // @notice Transfers the ownership of an NFT from one address to another address // @dev This works identically to the other function with an extra data parameter, // except this function just sets data to "" // @param _from The current owner of the NFT // @param _to The new owner // @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); } // @notice Transfer a Cutie owned by another address, for which the calling address // has been granted transfer approval by the owner. // @param _from The address that owns the Cutie to be transferred. // @param _to Any address, including the caller address, can take ownership of the Cutie. // @param _tokenId The ID of the Cutie to be transferred. // @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused canBeStoredIn40Bits(_tokenId) { require(_to != address(0), "Wrong cutie destination"); require(_to != address(this), "Wrong cutie destination"); // Check for approval and valid ownership require(_isApprovedOrOwner(msg.sender, uint40(_tokenId)), "Caller is not owner nor approved"); require(_isOwner(_from, uint40(_tokenId)), "Wrong cutie owner"); // Reassign ownership, clearing pending approvals and emitting Transfer event. _transfer(_from, _to, uint40(_tokenId)); } // @notice Transfers a Cutie to another address. When transferring to a smart // contract, ensure that it is aware of ERC-721 (or BlockchainCuties specifically), // otherwise the Cutie may be lost forever. // @param _to The address of the recipient, can be a user or contract. // @param _cutieId The ID of the Cutie to transfer. // @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _cutieId) public whenNotPaused canBeStoredIn40Bits(_cutieId) { require(_to != address(0), "Wrong cutie destination"); // You can only send your own cutie. require(_isOwner(msg.sender, uint40(_cutieId)), "Caller is not a cutie owner"); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, uint40(_cutieId)); } function transferBulk(address[] to, uint[] tokens) public whenNotPaused { require(to.length == tokens.length); for (uint i = 0; i < to.length; i++) { transfer(to[i], tokens[i]); } } function transferMany(address to, uint[] tokens) public whenNotPaused { for (uint i = 0; i < tokens.length; i++) { transfer(to, tokens[i]); } } // @notice Grant another address the right to transfer a particular Cutie via transferFrom(). // This flow is preferred for transferring NFTs to contracts. // @param _to The address to be granted transfer approval. Pass address(0) to clear all approvals. // @param _cutieId The ID of the Cutie that can be transferred if this call succeeds. // @dev Required for ERC-721 compliance. function approve(address _to, uint256 _cutieId) public whenNotPaused canBeStoredIn40Bits(_cutieId) { // Only cutie's owner can grant transfer approval. require(_isOwner(msg.sender, uint40(_cutieId)), "Caller is not a cutie owner"); require(msg.sender != _to, "Approval to current owner"); // Registering approval replaces any previous approval. _approve(uint40(_cutieId), _to); // Emit approval event. emit Approval(msg.sender, _to, _cutieId); } function delegatedApprove(address _from, address _to, uint40 _cutieId) external whenNotPaused onlyGame { require(_isOwner(_from, _cutieId), "Wrong cutie owner"); _approve(_cutieId, _to); } function approveAndCall(address _spender, uint _tokenId, bytes data) external whenNotPaused returns (bool) { approve(_spender, _tokenId); TokenRecipientInterface(_spender).receiveApproval(msg.sender, _tokenId, this, data); return true; } // @notice Enable or disable approval for a third party ("operator") to manage // all your asset. // @dev Emits the ApprovalForAll event // @param _operator Address to add to the set of authorized operators. // @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { require(_operator != msg.sender, "Approve to caller"); if (_approved) { addressToApprovedAll[msg.sender][_operator] = true; } else { delete addressToApprovedAll[msg.sender][_operator]; } emit ApprovalForAll(msg.sender, _operator, _approved); } // @notice Get the approved address for a single NFT // @dev Throws if `_tokenId` is not a valid NFT // @param _tokenId The NFT to find the approved address for // @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view canBeStoredIn40Bits(_tokenId) returns (address) { require(_tokenId <= total, "Cutie not exists"); return cutieIndexToApproved[uint40(_tokenId)]; } // @notice Query if an address is an authorized operator for another address // @param _owner The address that owns the NFTs // @param _operator The address that acts on behalf of the owner // @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return addressToApprovedAll[_owner][_operator]; } // @dev Returns whether `spender` is allowed to manage `cutieId`. function _isApprovedOrOwner(address spender, uint40 cutieId) internal view returns (bool) { require(_exists(cutieId), "Cutie not exists"); address owner = cutieIndexToOwner[cutieId]; return (spender == owner || _approvedFor(spender, cutieId) || isApprovedForAll(owner, spender)); } // @dev Checks if a given address is the current owner of a certain Cutie. // @param _claimant the address we are validating against. // @param _cutieId cutie id, only valid when > 0 function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool) { return cutieIndexToOwner[_cutieId] == _claimant; } function _exists(uint40 _cutieId) internal view returns (bool) { return cutieIndexToOwner[_cutieId] != address(0); } // @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 done on purpose: // _approve() and transferFrom() are used together for putting Cuties on auction. // There is no value in spamming the log with Approval events in that case. function _approve(uint40 _cutieId, address _approved) internal { cutieIndexToApproved[_cutieId] = _approved; } // @dev Checks if a given address currently has transferApproval for a certain Cutie. // @param _claimant the address we are confirming the cutie is approved for. // @param _cutieId cutie id, only valid when > 0 function _approvedFor(address _claimant, uint40 _cutieId) internal view returns (bool) { return cutieIndexToApproved[_cutieId] == _claimant; } // @dev Assigns ownership of a particular Cutie to an address. function _transfer(address _from, address _to, uint40 _cutieId) internal { // since the number of cuties is capped to 2^40 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership cutieIndexToOwner[_cutieId] = _to; // When creating new cuties _from is 0x0, but we cannot account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete cutieIndexToApproved[_cutieId]; } // Emit the transfer event. emit Transfer(_from, _to, _cutieId); } // 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. function _isContract(address _account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_account) } return size > 0; } // @dev For transferring a cutie owned by this contract to the specified address. // Used to rescue lost cuties. (There is no "proper" flow where this contract // should be the owner of any Cutie. This function exists for us to reassign // the ownership of Cuties that users may have accidentally sent to our address.) // @param _cutieId - ID of cutie // @param _recipient - Address to send the cutie to function restoreCutieToAddress(uint40 _cutieId, address _recipient) external whenNotPaused onlyOperator { require(_isOwner(this, _cutieId)); _transfer(this, _recipient, _cutieId); } // @dev An method that creates a new cutie and stores it. This // method does not check anything and should only be called when the // input data is valid for sure. Will generate both a Birth event // and a Transfer event. // @param _momId The cutie ID of the mom of this cutie (zero for gen0) // @param _dadId The cutie ID of the dad of this cutie (zero for gen0) // @param _generation The generation number of this cutie, must be computed by caller. // @param _genes The cutie's genetic code. // @param _owner The initial owner of this cutie, must be non-zero (except for the unCutie, ID 0) function createCutie( address _owner, uint40 _momId, uint40 _dadId, uint16 _generation, uint16 _cooldownIndex, uint256 _genes, uint40 _birthTime ) external whenNotPaused onlyGame returns (uint40) { Cutie memory _cutie = Cutie({ genes : _genes, birthTime : _birthTime, cooldownEndTime : 0, momId : _momId, dadId : _dadId, cooldownIndex : _cooldownIndex, generation : _generation, optional : 0 }); total++; uint256 newCutieId256 = total; // Check if id can fit into 40 bits require(newCutieId256 <= 0xFFFFFFFFFF); uint40 newCutieId = uint40(newCutieId256); cuties[newCutieId] = _cutie; // This will assign ownership, as well as emit the Transfer event as per ERC721 draft _transfer(0, _owner, newCutieId); return newCutieId; } // @dev Recreate the cutie if it stuck on old contracts and cannot be migrated smoothly function restoreCutie( address owner, uint40 id, uint256 _genes, uint40 _momId, uint40 _dadId, uint16 _generation, uint40 _cooldownEndTime, uint16 _cooldownIndex, uint40 _birthTime ) external whenNotPaused onlyGame { require(owner != address(0), "Restore to zero address"); require(total >= id, "Cutie restore is not allowed"); require(cuties[id].birthTime == 0, "Cutie overwrite is forbidden"); Cutie memory cutie = Cutie({ genes: _genes, momId: _momId, dadId: _dadId, generation: _generation, cooldownEndTime: _cooldownEndTime, cooldownIndex: _cooldownIndex, birthTime: _birthTime, optional: 0 }); cuties[id] = cutie; cutieIndexToOwner[id] = owner; ownershipTokenCount[owner]++; } // @notice Returns all the relevant information about a certain cutie. // @param _id The ID of the cutie of interest. function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ) { require(_exists(_id), "Cutie not exists"); Cutie storage cutie = cuties[_id]; genes = cutie.genes; birthTime = cutie.birthTime; cooldownEndTime = cutie.cooldownEndTime; momId = cutie.momId; dadId = cutie.dadId; cooldownIndex = cutie.cooldownIndex; generation = cutie.generation; } function getGenes(uint40 _id) external view returns (uint256) { return cuties[_id].genes; } function setGenes(uint40 _id, uint256 _genes) external whenNotPaused onlyGame { cuties[_id].genes = _genes; } function getCooldownEndTime(uint40 _id) external view returns (uint40) { return cuties[_id].cooldownEndTime; } function setCooldownEndTime(uint40 _id, uint40 _cooldownEndTime) external whenNotPaused onlyGame { cuties[_id].cooldownEndTime = _cooldownEndTime; } function getCooldownIndex(uint40 _id) external view returns (uint16) { return cuties[_id].cooldownIndex; } function setCooldownIndex(uint40 _id, uint16 _cooldownIndex) external whenNotPaused onlyGame { cuties[_id].cooldownIndex = _cooldownIndex; } function getGeneration(uint40 _id) external view returns (uint16) { return cuties[_id].generation; } function setGeneration(uint40 _id, uint16 _generation) external whenNotPaused onlyGame { cuties[_id].generation = _generation; } function getOptional(uint40 _id) external view returns (uint64) { return cuties[_id].optional; } function setOptional(uint40 _id, uint64 _optional) external whenNotPaused onlyGame { cuties[_id].optional = _optional; } }
Transfers the ownership of an NFT from one address to another address This works identically to the other function with an extra data parameter, except this function just sets data to "" _from The current owner of the NFT _to The new owner _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); }
253,400
./full_match/5/0xE2C1706C78FA0f2B5221ab51EEC42f75574C2C09/sources/contracts/L1/messaging/L1CrossDomainMessengerFast.sol
Verifies that the state root within an inclusion proof is valid. _proof Message inclusion proof. return Whether or not the provided proof is valid./ not check time after challenge period
function _verifyStateRootProof(L2MessageInclusionProof memory _proof) internal view returns (bool) { IStateCommitmentChain ovmStateCommitmentChain = IStateCommitmentChain( resolve("StateCommitmentChain") ); return ( ovmStateCommitmentChain.verifyStateCommitment( _proof.stateRoot, _proof.stateRootBatchHeader, _proof.stateRootProof ) ); }
1,895,406
./full_match/4/0xC209E294664C8Cb5B55EbF1CAE6CaCCd024Cb822/sources/contracts/ERC721A.sol
Mints `quantity` tokens and transfers them to `to`. Requirements: - `to` cannot be the zero address. - `quantity` must be greater than 0. Emits a {Transfer} event for each mint./ Overflows are incredibly unrealistic. `balance` and `numberMinted` have a maximum limit of 264. `tokenId` has a maximum limit of 2256. Updates: - `balance += quantity`. - `numberMinted += quantity`. We can directly add to the `balance` and `numberMinted`. Updates: - `address` to the owner. - `startTimestamp` to the timestamp of minting. - `burned` to `false`. - `nextInitialized` to `quantity == 1`.
function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 tokenId = startTokenId; uint256 end = startTokenId + quantity; do { emit Transfer(address(0), to, tokenId++); } while (tokenId < end); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
727,674
//Address: 0x14f37b574242d366558db61f3335289a5035c506 //Contract name: HackerGold //Balance: 0 Ether //Verification Date: 1/9/2017 //Transacion Count: 4373 // CODE STARTS HERE pragma solidity ^ 0.4 .0; /* * Token - is a smart contract interface * for managing common functionality of * a token. * * ERC.20 Token standard: https://github.com/eth ereum/EIPs/issues/20 */ contract TokenInterface { // total amount of tokens uint totalSupplyVar; /** * * balanceOf() - constant function check concrete tokens balance * * @param owner - account owner * * @return the value of balance */ function balanceOf(address owner) constant returns(uint256 balance); function transfer(address to, uint256 value) returns(bool success); function transferFrom(address from, address to, uint256 value) returns(bool success); /** * * approve() - function approves to a person to spend some tokens from * owner balance. * * @param spender - person whom this right been granted. * @param value - value to spend. * * @return true in case of succes, otherwise failure * */ function approve(address spender, uint256 value) returns(bool success); /** * * allowance() - constant function to check how much is * permitted to spend to 3rd person from owner balance * * @param owner - owner of the balance * @param spender - permitted to spend from this balance person * * @return - remaining right to spend * */ function allowance(address owner, address spender) constant returns(uint256 remaining); function totalSupply() constant returns(uint256 totalSupply) { return totalSupplyVar; } // events notifications event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^ 0.4 .2; /* * StandardToken - is a smart contract * for managing common functionality of * a token. * * ERC.20 Token standard: * https://github.com/eth ereum/EIPs/issues/20 */ contract StandardToken is TokenInterface { // token ownership mapping(address => uint256) balances; // spending permision management mapping(address => mapping(address => uint256)) allowed; function StandardToken() {} /** * transfer() - transfer tokens from msg.sender balance * to requested account * * @param to - target address to transfer tokens * @param value - ammount of tokens to transfer * * @return - success / failure of the transaction */ function transfer(address to, uint256 value) returns(bool success) { if (balances[msg.sender] >= value && value > 0) { // do actual tokens transfer balances[msg.sender] -= value; balances[to] += value; // rise the Transfer event Transfer(msg.sender, to, value); return true; } else { return false; } } /** * transferFrom() - used to move allowed funds from other owner * account * * @param from - move funds from account * @param to - move funds to account * @param value - move the value * * @return - return true on success false otherwise */ function transferFrom(address from, address to, uint256 value) returns(bool success) { if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { // do the actual transfer balances[from] -= value; balances[to] += value; // addjust the permision, after part of // permited to spend value was used allowed[from][msg.sender] -= value; // rise the Transfer event Transfer(from, to, value); return true; } else { return false; } } /** * * balanceOf() - constant function check concrete tokens balance * * @param owner - account owner * * @return the value of balance */ function balanceOf(address owner) constant returns(uint256 balance) { return balances[owner]; } /** * * approve() - function approves to a person to spend some tokens from * owner balance. * * @param spender - person whom this right been granted. * @param value - value to spend. * * @return true in case of succes, otherwise failure * */ function approve(address spender, uint256 value) returns(bool success) { // now spender can use balance in // ammount of value from owner balance allowed[msg.sender][spender] = value; // rise event about the transaction Approval(msg.sender, spender, value); return true; } /** * * allowance() - constant function to check how mouch is * permited to spend to 3rd person from owner balance * * @param owner - owner of the balance * @param spender - permited to spend from this balance person * * @return - remaining right to spend * */ function allowance(address owner, address spender) constant returns(uint256 remaining) { return allowed[owner][spender]; } } pragma solidity ^ 0.4 .0; /** * * @title Hacker Gold * * The official token powering the hack.ether.camp virtual accelerator. * This is the only way to acquire tokens from startups during the event. * * Whitepaper https://hack.ether.camp/whitepaper * */ contract HackerGold is StandardToken { // Name of the token string public name = "HackerGold"; // Decimal places uint8 public decimals = 3; // Token abbreviation string public symbol = "HKG"; // 1 ether = 200 hkg uint BASE_PRICE = 200; // 1 ether = 150 hkg uint MID_PRICE = 150; // 1 ether = 100 hkg uint FIN_PRICE = 100; // Safety cap uint SAFETY_LIMIT = 4000000 ether; // Zeros after the point uint DECIMAL_ZEROS = 1000; // Total value in wei uint totalValue; // Address of multisig wallet holding ether from sale address wallet; // Structure of sale increase milestones struct milestones_struct { uint p1; uint p2; uint p3; uint p4; uint p5; uint p6; } // Milestones instance milestones_struct milestones; /** * Constructor of the contract. * * Passes address of the account holding the value. * HackerGold contract itself does not hold any value * * @param multisig address of MultiSig wallet which will hold the value */ function HackerGold(address multisig) { wallet = multisig; // set time periods for sale milestones = milestones_struct( 1476972000, // P1: GMT: 20-Oct-2016 14:00 => The Sale Starts 1478181600, // P2: GMT: 03-Nov-2016 14:00 => 1st Price Ladder 1479391200, // P3: GMT: 17-Nov-2016 14:00 => Price Stable, // Hackathon Starts 1480600800, // P4: GMT: 01-Dec-2016 14:00 => 2nd Price Ladder 1481810400, // P5: GMT: 15-Dec-2016 14:00 => Price Stable 1482415200 // P6: GMT: 22-Dec-2016 14:00 => Sale Ends, Hackathon Ends ); // assign recovery balance totalSupplyVar = 16110893000; balances[0x342e62732b76875da9305083ea8ae63125a4e667] = 16110893000; totalValue = 85362 ether; } /** * Fallback function: called on ether sent. * * It calls to createHKG function with msg.sender * as a value for holder argument */ function() payable { createHKG(msg.sender); } /** * Creates HKG tokens. * * Runs sanity checks including safety cap * Then calculates current price by getPrice() function, creates HKG tokens * Finally sends a value of transaction to the wallet * * Note: due to lack of floating point types in Solidity, * contract assumes that last 3 digits in tokens amount are stood after the point. * It means that if stored HKG balance is 100000, then its real value is 100 HKG * * @param holder token holder */ function createHKG(address holder) payable { if (now < milestones.p1) throw; if (now >= milestones.p6) throw; if (msg.value == 0) throw; // safety cap if (getTotalValue() + msg.value > SAFETY_LIMIT) throw; uint tokens = msg.value * getPrice() * DECIMAL_ZEROS / 1 ether; totalSupplyVar += tokens; balances[holder] += tokens; totalValue += msg.value; if (!wallet.send(msg.value)) throw; } /** * Denotes complete price structure during the sale. * * @return HKG amount per 1 ETH for the current moment in time */ function getPrice() constant returns(uint result) { if (now < milestones.p1) return 0; if (now >= milestones.p1 && now < milestones.p2) { return BASE_PRICE; } if (now >= milestones.p2 && now < milestones.p3) { uint days_in = 1 + (now - milestones.p2) / 1 days; return BASE_PRICE - days_in * 25 / 7; // daily decrease 3.5 } if (now >= milestones.p3 && now < milestones.p4) { return MID_PRICE; } if (now >= milestones.p4 && now < milestones.p5) { days_in = 1 + (now - milestones.p4) / 1 days; return MID_PRICE - days_in * 25 / 7; // daily decrease 3.5 } if (now >= milestones.p5 && now < milestones.p6) { return FIN_PRICE; } if (now >= milestones.p6) { return 0; } } /** * Returns total stored HKG amount. * * Contract assumes that last 3 digits of this value are behind the decimal place. i.e. 10001 is 10.001 * Thus, result of this function should be divided by 1000 to get HKG value * * @return result stored HKG amount */ function getTotalSupply() constant returns(uint result) { return totalSupplyVar; } /** * It is used for test purposes. * * Returns the result of 'now' statement of Solidity language * * @return unix timestamp for current moment in time */ function getNow() constant returns(uint result) { return now; } /** * Returns total value passed through the contract * * @return result total value in wei */ function getTotalValue() constant returns(uint result) { return totalValue; } }
Returns total value passed through the contract return result total value in wei/
function getTotalValue() constant returns(uint result) { return totalValue; }
7,271,360
/* Copyright 2017-2018 RigoBlock, Rigo Investment Sagl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.0; import { DragoRegistryFace as DragoRegistry } from "../../DragoRegistry/DragoRegistryFace.sol"; import { AuthorityFace as Authority } from "../../authorities/Authority/AuthorityFace.sol"; import { VaultEventfulFace as VaultEventful } from "../../VaultEventful/VaultEventfulFace.sol"; import { VaultFactoryLibrary, Vault } from "../VaultFactoryLibrary/VaultFactoryLibrary.sol"; import { OwnedUninitialized as Owned } from "../../../utils/Owned/OwnedUninitialized.sol"; import { VaultFactoryFace } from "./VaultFactoryFace.sol"; /// @title Vault Factory contract - allows creation of new vaults. /// @author Gabriele Rigo - <gab@rigoblock.com> // solhint-disable-next-line contract VaultFactory is Owned, VaultFactoryFace { VaultFactoryLibrary.NewVault private libraryData; string public constant VERSION = "VF 0.5.2"; Data private data; struct Data { uint256 fee; address vaultRegistry; address payable vaultDao; address authority; mapping(address => address[]) vaults; } event VaultCreated( string name, string symbol, address indexed vault, address indexed owner, uint256 vaultId ); modifier whitelistedFactory(address _authority) { Authority auth = Authority(_authority); require(auth.isWhitelistedFactory(address(this))); _; } modifier whenFeePaid { require(msg.value >= data.fee); _; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyVaultDao { require(msg.sender == data.vaultDao); _; } constructor( address _registry, address payable _vaultDao, address _authority) public { data.vaultRegistry = _registry; data.vaultDao = _vaultDao; data.authority = _authority; owner = msg.sender; } /* * CORE FUNCTIONS */ /// @dev allows creation of a new vault /// @param _name String of the name /// @param _symbol String of the symbol /// @return Bool the transaction executed correctly function createVault(string calldata _name, string calldata _symbol) external payable whenFeePaid returns (bool success) { DragoRegistry registry = DragoRegistry(data.vaultRegistry); uint256 regFee = registry.getFee(); uint256 vaultId = registry.dragoCount(); require(createVaultInternal(_name, _symbol, msg.sender, vaultId)); assert(registry.register.value(regFee)( libraryData.newAddress, _name, _symbol, vaultId, msg.sender) ); return true; } /// @dev Allows factory owner to update the address of the dao/factory /// @dev Enables manual update of dao for single vaults /// @param _targetVault Address of the target vault /// @param _vaultDao Address of the new vault dao function setTargetVaultDao(address _targetVault, address _vaultDao) external onlyOwner { Vault vault = Vault(_targetVault); vault.changeVaultDao(_vaultDao); } /// @dev Allows vault dao/factory to update its address /// @dev Creates internal record /// @param _newVaultDao Address of the vault dao function changeVaultDao(address payable _newVaultDao) external onlyVaultDao { data.vaultDao = _newVaultDao; } /// @dev Allows owner to update the registry /// @param _newRegistry Address of the new registry function setRegistry(address _newRegistry) external onlyOwner { data.vaultRegistry = _newRegistry; } /// @dev Allows owner to set the address which can collect creation fees /// @param _vaultDao Address of the new vault dao/factory function setBeneficiary(address payable _vaultDao) external onlyOwner { data.vaultDao = _vaultDao; } /// @dev Allows owner to set the vault creation fee /// @param _fee Value of the fee in wei function setFee(uint256 _fee) external onlyOwner { data.fee = _fee; } /// @dev Allows owner to collect fees function drain() external onlyOwner { data.vaultDao.transfer(address(this).balance); } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Returns the address of the pool registry /// @return Address of the registry function getRegistry() external view returns (address) { return (data.vaultRegistry); } /// @dev Returns administrative data for this factory /// @return Address of the vault dao /// @return String of the version /// @return Number of the next vault from the registry function getStorage() external view returns ( address vaultDao, string memory version, uint256 nextVaultId ) { return ( vaultDao = data.vaultDao, version = VERSION, nextVaultId = getNextId() ); } /// @dev Returns the address of the logger contract /// @dev Queries from authority contract /// @return Address of the eventful contract function getEventful() external view returns (address) { Authority auth = Authority(data.authority); return auth.getVaultEventful(); } /// @dev Returns an array of vaults the owner has created /// @param _owner Address of the queried owner /// @return Array of vault addresses function getVaultsByAddress(address _owner) external view returns (address[] memory) { return data.vaults[_owner]; } /* * INTERNAL FUNCTIONS */ /// @dev Creates a vault and routes to eventful /// @param _name String of the name /// @param _symbol String of the symbol /// @param _owner Address of the owner /// @param _vaultId Number of the new vault Id /// @return Bool the transaction executed correctly function createVaultInternal( string memory _name, string memory _symbol, address _owner, uint256 _vaultId) internal returns (bool success) { Authority auth = Authority(data.authority); require(VaultFactoryLibrary.createVault( libraryData, _name, _symbol, _owner, _vaultId, data.authority) ); data.vaults[_owner].push(libraryData.newAddress); VaultEventful events = VaultEventful(auth.getVaultEventful()); require(events.createVault( _owner, libraryData.newAddress, _name, _symbol, _vaultId) ); auth.whitelistVault(libraryData.newAddress, true); auth.whitelistUser(_owner, true); emit VaultCreated(_name, _symbol, libraryData.newAddress, _owner, _vaultId); return true; } /// @dev Returns the next Id for a vault /// @return Number of the next Id from the registry function getNextId() internal view returns (uint256 nextVaultId) { DragoRegistry registry = DragoRegistry(data.vaultRegistry); nextVaultId = registry.dragoCount(); } }
Allows owner to update the registry _newRegistry Address of the new registry
function setRegistry(address _newRegistry) external onlyOwner { data.vaultRegistry = _newRegistry; }
15,857,326
./full_match/1/0x8430Be7B8fd28Cc58EA70A25C9c7A624F26f5D09/sources/src/core/processors/RollupProcessorV2.sol
A function which constructs a FullBridgeCallData struct based on values from `_encodedBridgeCallData` _encodedBridgeCallData a bit-array that contains data describing a specific bridge call Structure of the bit array is as follows (starting at the least significant bit): | bit range | parameter | description | | 0 - 32 | bridgeAddressId | The address ID. Bridge address = `supportedBridges[bridgeAddressId]` | | 32 - 62 | inputAssetIdA | First input asset ID. | | 62 - 92 | inputAssetIdB | Second input asset ID. Must be 0 if bridge does not have a 2nd input asset. | | 92 - 122 | outputAssetIdA | First output asset ID. | | 122 - 152 | outputAssetIdB | Second output asset ID. Must be 0 if bridge does not have a 2nd output asset. | | 152 - 184 | bitConfig | Bit-array that contains boolean bridge settings. | | 184 - 248 | auxData | 64 bits of custom data to be passed to the bridge contract. Structure of auxData is defined/checked by the bridge contract. | Structure of the `bitConfig` parameter is as follows | bit | parameter | description | | 0 | secondInputInUse | Does the bridge have a second input asset? | | 1 | secondOutputInUse | Does the bridge have a second output asset? | Note: Virtual assets are assets that don't have an ERC20 token analogue and exist solely as notes within the Aztec network. They can be created/spent within bridge calls. They are used to enable bridges to track internally-defined data without having to mint a new token on-chain. An example use of a virtual asset would be a virtual loan asset that tracks an outstanding debt that must be repaid to recover a collateral deposited into the bridge. return fullBridgeCallData a struct that contains information defining a specific bridge call/ bitConfig = bit mask that contains bridge ID settings bit 0 = second input asset in use? bit 1 = second output asset in use? potential conflicting states that are explicitly ruled out by circuit constraints:
function getFullBridgeCallData(uint256 _encodedBridgeCallData) internal view returns (FullBridgeCallData memory fullBridgeCallData) { assembly { mstore( add(fullBridgeCallData, 0x40), and(shr(INPUT_ASSET_ID_A_SHIFT, _encodedBridgeCallData), MASK_THIRTY_BITS) mstore( add(fullBridgeCallData, 0x60), and(shr(INPUT_ASSET_ID_B_SHIFT, _encodedBridgeCallData), MASK_THIRTY_BITS) mstore( add(fullBridgeCallData, 0x80), and(shr(OUTPUT_ASSET_ID_A_SHIFT, _encodedBridgeCallData), MASK_THIRTY_BITS) mstore( add(fullBridgeCallData, 0xa0), and(shr(OUTPUT_ASSET_ID_B_SHIFT, _encodedBridgeCallData), MASK_THIRTY_BITS) mstore( add(fullBridgeCallData, 0xc0), and(shr(AUX_DATA_SHIFT, _encodedBridgeCallData), MASK_SIXTY_FOUR_BITS) mstore( add(fullBridgeCallData, 0xe0), and(shr(add(INPUT_ASSET_ID_A_SHIFT, VIRTUAL_ASSET_ID_FLAG_SHIFT), _encodedBridgeCallData), 1) mstore( add(fullBridgeCallData, 0x100), and(shr(add(INPUT_ASSET_ID_B_SHIFT, VIRTUAL_ASSET_ID_FLAG_SHIFT), _encodedBridgeCallData), 1) mstore( add(fullBridgeCallData, 0x120), and(shr(add(OUTPUT_ASSET_ID_A_SHIFT, VIRTUAL_ASSET_ID_FLAG_SHIFT), _encodedBridgeCallData), 1) mstore( add(fullBridgeCallData, 0x140), and(shr(add(OUTPUT_ASSET_ID_B_SHIFT, VIRTUAL_ASSET_ID_FLAG_SHIFT), _encodedBridgeCallData), 1) let bitConfig := and(shr(BITCONFIG_SHIFT, _encodedBridgeCallData), MASK_THIRTY_TWO_BITS) } fullBridgeCallData.bridgeAddress = supportedBridges[fullBridgeCallData.bridgeAddressId - 1]; fullBridgeCallData.bridgeGasLimit = bridgeGasLimits[fullBridgeCallData.bridgeAddressId]; if (!fullBridgeCallData.secondInputInUse && fullBridgeCallData.inputAssetIdB > 0) { revert INCONSISTENT_BRIDGE_CALL_DATA(); } if (!fullBridgeCallData.secondOutputInUse && fullBridgeCallData.outputAssetIdB > 0) { revert INCONSISTENT_BRIDGE_CALL_DATA(); } if ( fullBridgeCallData.secondInputInUse && (fullBridgeCallData.inputAssetIdA == fullBridgeCallData.inputAssetIdB) ) { revert BRIDGE_WITH_IDENTICAL_INPUT_ASSETS(fullBridgeCallData.inputAssetIdA); } if (secondOutputReal && fullBridgeCallData.outputAssetIdA == fullBridgeCallData.outputAssetIdB) { revert BRIDGE_WITH_IDENTICAL_OUTPUT_ASSETS(fullBridgeCallData.outputAssetIdA); } }
4,874,868
/** *Submitted for verification at Etherscan.io on 2021-10-18 */ // 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); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } contract tacoDrawing { function _getTacoDrawing() internal pure returns (string memory) { string memory svg = string(abi.encodePacked( '<g transform="translate(70,40) scale(1.8)"><polygon id="TortillaFront" class="cls-1" points="29.56 80.48 0.88 75.68 8.17 36.13 52.68 0.86 94.81 18.25 29.56 80.48"/>', '<polygon id="Protein" class="cls-2" points="13.79 75.05 11.52 70.02 8.06 66.04 9.7 59.82 8.06 52.99 21.95 39.24 31.85 27.72 60.21 27.21 30.57 76.5 24.21 78.22 19.48 75.99 13.79 75.05"/>' '<polygon id="Sauce" class="cls-3" points="13.27 40.78 7.96 46.1 13.14 53.67 20.51 51.63 27.02 56.3 36.19 52.27 37.52 17.88 21.71 31.6 13.27 40.78"/>', '<polygon id="Veggie" class="cls-4" points="23.57 30.82 14.11 28.23 21.41 18.35 27.05 23.18 25.43 14.58 34 11.98 35.99 21.06 39.1 12.1 43.83 12.79 43.99 20.43 54.66 15.58 63.15 18.83 52.58 26.48 56.23 37.29 46.58 41.06 42.84 44.7 35.81 36.2 37.33 44.45 25.88 46.38 28.06 36.7 23.67 40.98 14.11 35.53 23.57 30.82"/>', '<polygon id="TortillaBack" class="cls-1" points="29.56 80.48 37.77 35.34 76.91 5.1 110.01 24.16 122.46 60.03 83.5 73.33 29.56 80.48"/>', '<g id="garnish">', '<rect class="cls-5" x="135.54" y="84.92" width="4.2" height="4.2" transform="matrix(0.82, -0.57, 0.57, 0.82, -134.49, 38.87)"/>', '<path d="M138,85.15l1.54,2.21L137.3,88.9l-1.54-2.22L138,85.15m.38-2.09-4.68,3.25L136.92,91l4.68-3.25-3.25-4.68Z" transform="translate(-109.44 -55.14)"/>', '<rect class="cls-5" x="145.88" y="82.09" width="4.2" height="4.2" transform="translate(-74.54 156.33) rotate(-78.02)"/>', '<path d="M146.94,82.59l2.64.56L149,85.79l-2.64-.56.56-2.64m-1.16-1.77-1.18,5.57,5.57,1.18L151.36,82l-5.58-1.18Z" transform="translate(-109.44 -55.14)"/>', '<rect class="cls-5" x="148.04" y="75.25" width="4.2" height="4.2" transform="translate(-127.84 11.31) rotate(-23.56)"/>', '<path d="M150.84,75.57,151.92,78l-2.48,1.08-1.07-2.47,2.47-1.08m.77-2-5.22,2.27,2.28,5.22,5.22-2.27-2.28-5.22Z" transform="translate(-109.44 -55.14)"/>', '<rect class="cls-5" x="136.82" y="76.84" width="4.2" height="4.2" transform="translate(-94.3 124.85) rotate(-68.84)"/>', '<path d="M138.14,77.2l2.52,1-1,2.52-2.51-1,1-2.51m-.85-1.94-2.06,5.31,5.31,2.06,2.06-5.31-5.31-2.06Z" transform="translate(-109.44 -55.14)"/>', '</g></g>', '</svg>' )); return svg; } } contract TacosForAdventurers is ERC721Enumerable, ReentrancyGuard, Ownable, tacoDrawing { using ToColor for bytes3; string[] private sideEffect = [ "Diarrhea", "Nausea", "Indigestion", "Heartburn", "MeatSweat", "Drowsiness", "Gas", "Obesity", "Cancer", "Stomach Ulcers", "Acid Reflux", "Fiery Poop", "Bat Plague" ]; string[] private magicEffect = [ "Fire breathing", "Thunderbolt", "Flash", "Warp", "Poison", "Frost Breath", "Blizzard", "Holy Light", "Ice Spike", "Avalanche", "Wind Scythe", "Gust", "Fire Whip" ]; string[] private stat = [ "Strength", "Constitution", "Dexterity", "Intelligence", "Wisdom", "Charisma" ]; string[] private suffixes = [ "of Power", "of Giants", "of Mice", "of Skill", "of Perfection", "of Brilliance", "of Anger", "of Rage", "of Fury", "of Bats", "of the Angels", "of Volcanoes", "of the Sea", "of the Ox", "of Light" ]; string[] private namePrefixes = [ "Explosive", "Fiery", "Spicy", "Glowing", "Bloody", "Glorious", "Sharp", "Jagged", "Sloppy", "Slippery", "Giant", "Twisted", "Noisy", "Silent", "Hard", "Painful", "Mortal", "Orgasmic", "Pleasant", "Speedy", "Slow", "Turbulent", "Deep", "Wistful", "Damning", "Shimmering", "Endless", "Stinky", "Shimmery", "Steady", "Revolutionary", "Pious", "Distressed", "Gratifying", "Perplexing", "Filthy", "Sticky", "Messy", "Creamy", "Fragmented", "Billowing", "Incendiary", "Starry", "Colossal", "Shameful", "Fantastic", "Odd", "Putrid", "Wicked", "Super", "Weak", "Mediocre", "Sore", "Terrible", "Tough", "Wild", "Aching", "Aggravating", "Ambitious", "Anguished", "Awkward", "Belated", "Brisk", "Coarse", "Critical", "Cumbersome", "Dazzling", "Deafening", "Dense", "Double", "Ultra","Minor", "Major", "Dismal", "Filthy", "Guilty", "Hideous", "Humuliating", "Irritating", "Itchy", "Juicy", "Kaleidoscope", "Shattered", "Mysterious" ]; function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getSideEffect(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "EFFECT", sideEffect); } function getMagicEffect(uint256 tokenId) public view returns (string memory) { return pluck(tokenId, "MAGIC", magicEffect); } function getStat(uint256 tokenId) public view returns (string memory) { uint256 rand = random(string(abi.encodePacked('STAT', toString(tokenId)))); string memory output = stat[rand % stat.length]; uint256 greatness = rand % 10; if(greatness == 0){ return string(abi.encodePacked(output, " +1")); } else { return string(abi.encodePacked(output, " +", toString(greatness))); } } function randomColor(string memory input, string memory input2) internal pure returns (bytes3) { bytes3 color; bytes32 predictableRandom = keccak256(abi.encodePacked(input, input2)); color = bytes2(predictableRandom[0]) | ( bytes2(predictableRandom[1]) >> 8 ) | ( bytes3(predictableRandom[2]) >> 16 ); return color; } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; uint256 greatness = rand % 15; if (greatness > 5) { output = string(abi.encodePacked(output, " ", suffixes[rand % suffixes.length])); } if (greatness >= 13) { string[2] memory name; name[0] = namePrefixes[rand % namePrefixes.length]; if (greatness == 13) { output = string(abi.encodePacked(name[0], " ", output)); } else { output = string(abi.encodePacked(name[0], " ", output, " +1")); } } return output; } function tokenURI(uint256 tokenId) override public view returns (string memory) { require(tokenId < 3001, "Theres no such Taco in existance"); string[10] memory color; color[0] = '<svg id="Taco" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 350 350"> <defs><style>.base { fill: white; font-family: monospace; font-size: 11px; }.cls-1 {fill: #'; color[1] = randomColor("TortillaFront", toString(tokenId)).toColor(); color[2] = '}.cls-1, .cls-2, .cls-3, .cls-4 {stroke: #000;stroke-miterlimit: 10;stroke-width: 1.5px;}.cls-2 {fill: #'; color[3] = randomColor("Protein", toString(tokenId)).toColor(); color[4] = '}.cls-3 {fill: #'; color[5] = randomColor("Sauce", toString(tokenId)).toColor(); color[6] = '}.cls-4 {fill: #'; color[7] = randomColor("Veggie", toString(tokenId)).toColor(); color[8] = '}.cls-5 {fill: #'; color[9] = randomColor("TortillaBack", toString(tokenId)).toColor(); string[7] memory svgText; svgText[0] = '}</style></defs><rect width="100%" height="100%" fill="#1d1d1d" /> <text x="50%" y="59%" class="base" text-anchor="middle">Magic Spell :</text><text x="50%" y="63%" class="base" text-anchor="middle">'; svgText[1] = getMagicEffect(tokenId); svgText[2] ='</text><text x="50%" y="74%" class="base" text-anchor="middle">Stat Modifier :</text><text x="50%" y="78%" class="base" text-anchor="middle">'; svgText[3] = getStat(tokenId); svgText[4] = '</text><text x="50%" y="89%" class="base" text-anchor="middle">Side Effect :</text><text x="50%" y="93%" class="base" text-anchor="middle">'; svgText[5] = getSideEffect(tokenId); svgText[6] = '</text>'; string memory output = string(abi.encodePacked(color[0], color[1], color[2], color[3], color[4])); output = string(abi.encodePacked(output, color[5], color[6], color[7], color[8], color[9])); string memory outputText = string(abi.encodePacked(svgText[0], svgText[1], svgText[2], svgText[3])); outputText = string(abi.encodePacked(outputText, svgText[4], svgText[5], svgText[6])); string memory outputMerge = string(abi.encodePacked(output, outputText)); string memory Taco = _getTacoDrawing(); outputMerge = string(abi.encodePacked(outputMerge, Taco)); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Taco #', toString(tokenId), '", "description": "Tacos for adventurers are generated and stored on chain. Each Taco has a magic power granted and stat modifiers, however... they have side effects, functionality are for others to interpret. Feel free to use these Tacos in any way you want.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(outputMerge)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } // function claim(uint256 tokenId) public nonReentrant { // require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); // _safeMint(_msgSender(), tokenId); //} function buyTaco(uint taconum) public payable nonReentrant { uint _totalSupply = totalSupply(); require((taconum + balanceOf(msg.sender)) <= 5 , "No more tacos for you!"); require(_totalSupply < 2980, "El changarro has closed homie"); require(_totalSupply + taconum <= 2980, "Theres not enough ingridients to make that amount of tacos"); require(taconum > 0 && taconum <= 5, "maximum order of tacos is 5"); require(msg.value >= 0.01 ether * taconum, "you need more itirium..."); for (uint i = 0; i < taconum; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 2980 && tokenId < 3001, "Token ID invalid"); _safeMint(owner(), tokenId); } function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("TacosForAdventurers", "TACOS") Ownable() {} } library ToColor { bytes16 internal constant ALPHABET = '0123456789abcdef'; function toColor(bytes3 value) internal pure returns (string memory) { bytes memory buffer = new bytes(6); for (uint256 i = 0; i < 3; i++) { buffer[i*2+1] = ALPHABET[uint8(value[i]) & 0xf]; buffer[i*2] = ALPHABET[uint8(value[i]>>4) & 0xf]; } return string(buffer); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId);}
function buyTaco(uint taconum) public payable nonReentrant { uint _totalSupply = totalSupply(); require((taconum + balanceOf(msg.sender)) <= 5 , "No more tacos for you!"); require(_totalSupply < 2980, "El changarro has closed homie"); require(_totalSupply + taconum <= 2980, "Theres not enough ingridients to make that amount of tacos"); require(taconum > 0 && taconum <= 5, "maximum order of tacos is 5"); require(msg.value >= 0.01 ether * taconum, "you need more itirium..."); for (uint i = 0; i < taconum; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } }
6,805,548
./full_match/1/0xceC62ebf1cd98b91556D84eebd5F8542E301b8b1/sources/browser/AtlantisCore.sol
loop through all specified task IDs manually call process() - if the tx fails (due to task being executed while tx is in transit etc) we ignore it and proceed instead of reverting the entire tx
function bulkProcessGST(uint256[] calldata _taskIDs) external discountGST { for(uint x = 0; x < _taskIDs.length; x++) address(this).call(abi.encodeWithSignature("process(uint256,address)", _taskIDs[x], msg.sender)); }
2,917,097
./full_match/80001/0xa06587A30877C44e16B7A83e03AB408aFadFE821/sources/contracts/Bridge.sol
Mint tokens if the user is permitted to mint assetType 0-native, 1-ERC20, 2-ERC721, 3-ERC1155 params targetBridgeParams structure (see definition in IBridge.sol) return True if tokens were minted successfully Verify the signature (contains v, r, s) using the domain separator This will prove that the user has burnt tokens on the target chain
function mintWithPermit(Assets assetType, targetBridgeParams calldata params) external nonReentrant returns(bool) { require(assetType != Assets.Native, "Bridge: wrong asset, can't mint native token"); address sender = msg.sender; bytes32 typeHash = EIP712Utils.getPermitTypeHash(sender, params, chain); signatureVerification(typeHash, params.nonce, params.v, params.r, params.s); mintAsset( assetType, sender, params.token, params.tokenId, params.amount ); emit Mint( assetType, sender, sender, params.amount, params.token, params.tokenId, chain ); return true; }
869,071
./partial_match/1/0x53cffb579143B08025D2f1353CCB7e36D1b9CC94/sources/contracts/DelegatorInterface.sol
delegate all other functions to current implementation
function _fallback() internal { if (msg.data.length > 0) { (bool success,) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success } } }
4,294,297
./partial_match/1/0x6FAEB511989E280D3A51ca45ED756C90e736b012/sources/@violetprotocol/mauve-swap-router-contracts/contracts/SwapRouter.sol
@inheritdoc ISwapRouter use amountIn == Constants.CONTRACT_BALANCE as a flag to swap the entire balance of the contract the outputs of prior swaps become the inputs to subsequent ones decide whether to continue or terminate
function exactInput(ExactInputParams memory params) external payable override onlySelfMulticall returns (uint256 amountOut) { bool hasAlreadyPaid; if (params.amountIn == Constants.CONTRACT_BALANCE) { hasAlreadyPaid = true; (address tokenIn, , ) = params.path.decodeFirstPool(); params.amountIn = IERC20(tokenIn).balanceOf(address(this)); } address payer = hasAlreadyPaid ? address(this) : msg.sender; while (true) { bool hasMultiplePools = params.path.hasMultiplePools(); params.amountIn = exactInputInternal( params.amountIn, 0, SwapCallbackData({ payer: payer }) ); if (hasMultiplePools) { payer = address(this); params.path = params.path.skipToken(); amountOut = params.amountIn; break; } } require(amountOut >= params.amountOutMinimum, 'Too little received'); }
15,680,973
./full_match/1/0xeF6303006a994f469Ef0FBDe20b269e804adB985/sources/src/Staking/StakingV1.sol
allow removing the lock duration, but not setting it directly. this removes the possibility of creating a long lock duration after people have deposited their tokens, essentially turning the staking contract into a honeypot. removing the lock is necessary in case of emergencies, like migrating to a new staking contract./
function removeLockDuration() external virtual override onlyAuthorized { _lockDurationDays = 0; }
16,403,959
pragma solidity ^0.5.12; library SafeMath { function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b); return c; } function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0); uint256 c = a / b; return c; } function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING uint256 internal _totalSupply; function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(msg.sender, to, value); return true; } function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[msg.sender][spender] = value; emit APPROVAL787(msg.sender, spender, value); return true; } function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(from, to, value); _allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value); return true; } function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB705(value); _balances[to] = _balances[to].ADD235(value); emit TRANSFER731(from, to, value); } } contract ERC20Mintable is ERC20 { string public name; string public symbol; uint8 public decimals; function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[to] = _balances[to].ADD235(amount); _totalSupply = _totalSupply.ADD235(amount); emit TRANSFER731(address(0), to, amount); } function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[from] = _balances[from].SUB705(amount); _totalSupply = _totalSupply.SUB705(amount); emit TRANSFER731(from, address(0), amount); } } // ----------- Aave ---------------- contract ILendingPoolAddressesProvider { function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING } interface ILendingPool { function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING function GETRESERVES689() external view; //inject NONSTANDARD NAMING } interface ILendingPoolCore { function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING } interface IAavePriceOracleGetter { function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING } interface IAToken { function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING } interface PriceOracle { function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING } // ---------- Compound ---------- interface CErc20 { function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING } interface CEth { function MINT397() external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING } interface Comptroller { function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING external returns (uint256[] memory); function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING external view returns (uint256, uint256, uint256); function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING } // ---------- kyber ---------- interface Exchange { function TRADE301( //inject NONSTANDARD NAMING address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId )external payable returns(uint); } // -----tCDP----- contract tCDPConstants { uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING //Compound Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING //AAVE ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING //Kyber Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING //rebalance target/boundary/size uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING } contract tCDP is ERC20Mintable, tCDPConstants{ using SafeMath for *; bool public isCompound; event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING constructor() public { symbol = "tETH-DAI"; name = "tokenized CDP ETH-DAI v1"; decimals = 18; address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1)); dai445.APPROVE277(address(cdai61), uint256(-1)); address[] memory cTokens = new address[](1); cTokens[0] = address(ceth501); uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens); require(errors[0] == 0, "Comptroller.enterMarkets failed."); dai445.APPROVE277(address(kybernetwork927), uint256(-1)); isCompound = FINDBESTRATE616(); } function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING require(_totalSupply < dust264, "initiated"); require(msg.value > dust264, "value too small"); if(isCompound) { ceth501.MINT397.value(msg.value)(); _MINT321(msg.sender, msg.value); require(cdai61.BORROW264(amount) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, amount); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215); _MINT321(msg.sender, msg.value); lendingPool.BORROW264(address(dai445), amount, 2, referral215); dai445.TRANSFER204(msg.sender, amount); } } function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return ceth501.BALANCEOFUNDERLYING788(address(this)); } else { address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21(); address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36); return IAToken(aETH).BALANCEOF767(address(this)); } } function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return cdai61.BORROWBALANCECURRENT444(address(this)); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); (, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this)); return borrowBalance; } } function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); uint256 amount = msg.value; uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797()); uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797()); _MINT321(msg.sender, tokenToMint); if(isCompound) { ceth501.MINT397.value(amount)(); require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, tokenToBorrow); } else{ // deposit ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215); // borrow lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215); // transfer dai445.TRANSFER204(msg.sender, tokenToBorrow); } return tokenToMint; } function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply); uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply); _BURN441(msg.sender, amount); dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay); if(isCompound) { require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed"); require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed"); } else { // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); // Dai.approve(lendingPoolCoreAddress, tokenToRepay); lendingPool.REPAY662(address(dai445), tokenToRepay, address(this)); // redeem IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(tokenToDraw); } (bool success, ) = msg.sender.call.value(tokenToDraw)(""); require(success, "Failed to transfer ether to msg.sender"); } function() external payable{} //true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160()); } function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400); } function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400); } function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9); } function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9); } function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 price; if(isCompound) { address oracle = comptroller75.ORACLE168(); PriceOracle priceOracle = PriceOracle(oracle); price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61)); } else { address oracleAddress = addressesprovider654.GETPRICEORACLE485(); IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress); price = priceOracle.GETASSETPRICE734(address(dai445)); } return price; } function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING uint256 price = GETUNDERLYINGPRICE929(); uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797()); return ratio; } function DELEVERAGE904() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() > upperbound23, "debt ratio is good"); uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18); if(isCompound) { require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed"); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); require(cdai61.REPAYBORROW515(income) == 0, "repay failed"); } else { // redeem address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(amount); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); // Dai.approve(lendingPoolCoreAddress, income); lendingPool.REPAY662(address(dai445), income, address(this)); } } function LEVERAGE920() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() < lowerbound414, "debt ratio is good"); uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18); if(isCompound) { require(cdai61.BORROW264(amount) == 0, "borrow failed"); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); ceth501.MINT397.value(income)(); } else { // borrow ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.BORROW264(address(dai445), amount, 2, referral215); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); // deposit lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215); } } function MIGRATE814() external { //inject NONSTANDARD NAMING if(FINDBESTRATE616() != isCompound) { uint256 _debt = DEBT567(); uint256 _collateral = COLLATERAL797(); dai445.TRANSFERFROM832(msg.sender, address(this), _debt); uint256 newBorrow = _debt.ADD235(2); if(isCompound) { require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed"); require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed"); ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215); lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215); isCompound = false; emit MIGRATION431(0x02); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); lendingPool.REPAY662(address(dai445), _debt, address(this)); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(_collateral); ceth501.MINT397.value(_collateral)(); require(cdai61.BORROW264(newBorrow) == 0, "borrow failed"); isCompound = true; emit MIGRATION431(0x01); } dai445.TRANSFER204(msg.sender, newBorrow); } } }
inject NONSTANDARD NAMING
function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success);
5,544,605
./full_match/1/0x600bAcC8D793Fe487703973987f1a3016c4BB8Ae/sources/pond.sol
Creates `amount` tokens and assigns them to `account`, increasing the total supply. - `account` cannot be the zero address./ Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); }
2,914,577
./partial_match/97/0x6fC5a01FDb790415c89deFA0C18416212A3a51C0/sources/BEP20Token.sol
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"); }
11,462,847
./full_match/1/0xbfEC5787799A179a2ec84b255FD288962D135494/sources/contracts/router01/OracleReader.sol
get the amount out from reserves does not take into account fees charged along the way factory the factory to derive a pair against tokenIn the token being pushed into the pair tokenOut the token to be pulled out amountIn the magnitude of the swap/
function amountOutFrom(address factory, address tokenIn, address tokenOut, uint256 amountIn) public view returns(uint256) { address pair = IUniswapV2Factory(factory).getPair(tokenIn, tokenOut); bool inIs0 = IUniswapV2Pair(pair).token0() == tokenIn; (uint256 reserveA, uint256 reserveB, ) = IUniswapV2Pair(pair).getReserves(); if (inIs0) { return (reserveB * amountIn) / reserveA; } return (reserveA * amountIn) / reserveB; }
16,409,905
./full_match/80001/0xdE888589c196890926daCf71770CB167691600bB/sources/contracts/MyERC721DropConditional.sol
Checks whether contract metadata can be set in the given execution context.
function _canSetContractURI() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); }
5,679,552
pragma solidity 0.5.9; import "./lib/ERC20Plus.sol"; import "./lib/FinalizableCrowdsale.sol"; import "./lib/Pausable.sol"; import "./FundsSplitterInterface.sol"; import "./StarEthRateInterface.sol"; import "./TokenSaleInterface.sol"; import "./Whitelist.sol"; /** * @title Token Sale contract - crowdsale of company tokens. * @author Gustavo Guimaraes - <gustavo@starbase.co> * @author Markus Waas - <markus@starbase.co> */ contract TokenSale is FinalizableCrowdsale, Pausable { uint256 public softCap; uint256 public crowdsaleCap; uint256 public tokensSold; // rate definitions uint256 public currentTargetRateIndex; uint256[] public targetRates; uint256[] public targetRatesTimestamps; // amount of raised money in STAR uint256 public starRaised; address public tokenOwnerAfterSale; bool public isWeiAccepted; bool public isMinting; bool private isInitialized; // external contracts Whitelist public whitelist; ERC20Plus public starToken; FundsSplitterInterface public wallet; StarEthRateInterface public starEthRateInterface; // The token being sold ERC20Plus public tokenOnSale; // Keep track of user investments mapping (address => uint256) public ethInvestments; mapping (address => uint256) public starInvestments; event TokenRateChanged(uint256 previousRate, uint256 newRate); event TokenStarRateChanged(uint256 previousStarRate, uint256 newStarRate); event TokenPurchaseWithStar( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @dev initialization function * @param _startTime The timestamp of the beginning of the crowdsale * @param _endTime Timestamp when the crowdsale will finish * @param _externalAddresses Containing all external addresses, see below * #param _whitelist contract containing the whitelisted addresses * #param _starToken STAR token contract address * #param _companyToken ERC20 contract address that has minting capabilities * #param _tokenOwnerAfterSale Address that this TokenSale will pass the token ownership to after it's finished. Only works when TokenSale mints tokens, otherwise must be `0x0`. * #param _starEthRateInterface The StarEthRate contract address . * #param _wallet FundsSplitter wallet that redirects funds to client and Starbase. * @param _softCap Soft cap of the token sale * @param _crowdsaleCap Cap for the token sale * @param _isWeiAccepted Bool for acceptance of ether in token sale * @param _isMinting Bool that indicates whether token sale mints ERC20 tokens on sale or simply transfers them * @param _targetRates Array of target rates. * @param _targetRatesTimestamps Array of target rates timestamps. */ function init( uint256 _startTime, uint256 _endTime, address[6] calldata _externalAddresses, // array avoids stack too deep error uint256 _softCap, uint256 _crowdsaleCap, bool _isWeiAccepted, bool _isMinting, uint256[] calldata _targetRates, uint256[] calldata _targetRatesTimestamps ) external { require(!isInitialized, "Contract instance was initialized already!"); isInitialized = true; require( _externalAddresses[0] != address(0) && _externalAddresses[1] != address(0) && _externalAddresses[2] != address(0) && _externalAddresses[4] != address(0) && _externalAddresses[5] != address(0) && _crowdsaleCap != 0, "Parameter variables cannot be empty!" ); require( _softCap < _crowdsaleCap, "SoftCap should be smaller than crowdsaleCap!" ); currentTargetRateIndex = 0; initCrowdsale(_startTime, _endTime); tokenOnSale = ERC20Plus(_externalAddresses[2]); whitelist = Whitelist(_externalAddresses[0]); starToken = ERC20Plus(_externalAddresses[1]); wallet = FundsSplitterInterface(uint160(_externalAddresses[5])); tokenOwnerAfterSale = _externalAddresses[3]; starEthRateInterface = StarEthRateInterface(_externalAddresses[4]); isWeiAccepted = _isWeiAccepted; isMinting = _isMinting; _owner = tx.origin; uint8 decimals = tokenOnSale.decimals(); softCap = _softCap.mul(10 ** uint256(decimals)); crowdsaleCap = _crowdsaleCap.mul(10 ** uint256(decimals)); targetRates = _targetRates; targetRatesTimestamps = _targetRatesTimestamps; if (isMinting) { require(tokenOwnerAfterSale != address(0), "tokenOwnerAfterSale cannot be empty when minting tokens!"); require(tokenOnSale.paused(), "Company token must be paused upon initialization!"); } else { require(tokenOwnerAfterSale == address(0), "tokenOwnerAfterSale must be empty when minting tokens!"); } verifyTargetRates(); } modifier isWhitelisted(address beneficiary) { require( whitelist.allowedAddresses(beneficiary), "Beneficiary not whitelisted!" ); _; } /** * @dev override fallback function. cannot use it */ function () external payable { revert("No fallback function defined!"); } /** * @dev function that allows token purchases with STAR or ETH * @param beneficiary Address of the purchaser */ function buyTokens(address beneficiary) public payable whenNotPaused isWhitelisted(beneficiary) { require(beneficiary != address(0), "Purchaser address cant be zero!"); require(validPurchase(), "TokenSale over or not yet started!"); require(tokensSold < crowdsaleCap, "All tokens sold!"); if (isMinting) { require(tokenOnSale.owner() == address(this), "The token owner must be contract address!"); } checkForNewRateAndUpdate(); if (!isWeiAccepted) { require(msg.value == 0, "Only purchases with STAR are allowed!"); } else if (msg.value > 0) { buyTokensWithWei(beneficiary); } // beneficiary must allow TokenSale address to transfer star tokens on its behalf uint256 starAllocationToTokenSale = starToken.allowance(msg.sender, address(this)); if (starAllocationToTokenSale > 0) { uint256 decimalCorrectionFactor = starEthRateInterface.decimalCorrectionFactor(); uint256 starEthRate = starEthRateInterface.starEthRate(); uint256 ethRate = targetRates[currentTargetRateIndex]; // calculate token amount to be created uint256 decimals = uint256(tokenOnSale.decimals()); uint256 tokens = (starAllocationToTokenSale .mul(ethRate) .mul(starEthRate)) .mul(10 ** decimals) // token decimals count .div(decimalCorrectionFactor) .div(1e18); // STAR decimals count // remainder logic if (tokensSold.add(tokens) > crowdsaleCap) { tokens = crowdsaleCap.sub(tokensSold); starAllocationToTokenSale = tokens .mul(1e18) .mul(decimalCorrectionFactor) .div(ethRate) .div(starEthRate) .div(10 ** decimals); } // update state starRaised = starRaised.add(starAllocationToTokenSale); starInvestments[beneficiary] = starInvestments[beneficiary].add(starAllocationToTokenSale); tokensSold = tokensSold.add(tokens); sendPurchasedTokens(beneficiary, tokens); emit TokenPurchaseWithStar(msg.sender, beneficiary, starAllocationToTokenSale, tokens); forwardsStarFunds(starAllocationToTokenSale); } } /** * @dev function that allows token purchases with Wei * @param beneficiary Address of the purchaser */ function buyTokensWithWei(address beneficiary) internal { uint256 weiAmount = msg.value; uint256 weiRefund; uint256 ethRate = targetRates[currentTargetRateIndex]; // calculate token amount to be created uint256 decimals = uint256(tokenOnSale.decimals()); uint256 tokens = weiAmount .mul(ethRate) .mul(10 ** decimals) // token decimals count .div(1e18); // ETH decimals count // remainder logic if (tokensSold.add(tokens) > crowdsaleCap) { tokens = crowdsaleCap.sub(tokensSold); weiAmount = tokens.mul(1e18).div(ethRate).div(10 ** decimals); weiRefund = msg.value.sub(weiAmount); } // update state weiRaised = weiRaised.add(weiAmount); ethInvestments[beneficiary] = ethInvestments[beneficiary].add(weiAmount); tokensSold = tokensSold.add(tokens); sendPurchasedTokens(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardsWeiFunds(weiRefund); } // isMinting checker -- it either mints ERC20 token or transfers them function sendPurchasedTokens( address _beneficiary, uint256 _tokens ) internal { if (isMinting) { tokenOnSale.mint(_beneficiary, _tokens); } else { tokenOnSale.transfer(_beneficiary, _tokens); } } // check for softCap achievement // @return true when softCap is reached function hasReachedSoftCap() public view returns (bool) { if (tokensSold >= softCap) return true; return false; } // override Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (tokensSold >= crowdsaleCap) return true; return super.hasEnded(); } /** * @dev override Crowdsale#validPurchase * @return true if the transaction can buy tokens */ function validPurchase() internal view returns (bool) { return now >= startTime && now <= endTime; } /** * @dev forward wei funds */ function forwardsWeiFunds(uint256 _weiRefund) internal { if (softCap == 0 || hasReachedSoftCap()) { if (_weiRefund > 0) msg.sender.transfer(_weiRefund); _forwardAnyFunds(); } } /** * @dev forward star funds */ function forwardsStarFunds(uint256 _value) internal { if (softCap > 0 && !hasReachedSoftCap()) { starToken.transferFrom(msg.sender, address(this), _value); } else { starToken.transferFrom(msg.sender, address(wallet), _value); _forwardAnyFunds(); } } /** * @dev withdraw funds for failed sales */ function withdrawUserFunds() public { require(hasEnded(), "Can only withdraw funds for ended sales!"); require( !hasReachedSoftCap(), "Can only withdraw funds for sales that didn't reach soft cap!" ); uint256 investedEthRefund = ethInvestments[msg.sender]; uint256 investedStarRefund = starInvestments[msg.sender]; require( investedEthRefund > 0 || investedStarRefund > 0, "You don't have any funds in the contract!" ); // prevent reentrancy attack ethInvestments[msg.sender] = 0; starInvestments[msg.sender] = 0; if (investedEthRefund > 0) { msg.sender.transfer(investedEthRefund); } if (investedStarRefund > 0) { starToken.transfer(msg.sender, investedStarRefund); } } function verifyTargetRates() internal view { require( targetRates.length == targetRatesTimestamps.length, 'Target rates and target rates timestamps lengths should match!' ); require(targetRates.length > 0, 'Target rates cannot be empty!'); require( targetRatesTimestamps[0] == startTime, 'First target rate timestamp should match startTime!' ); for (uint256 i = 0; i < targetRates.length; i++) { if (i > 0) { require( targetRatesTimestamps[i-1] < targetRatesTimestamps[i], 'Target rates timestamps should be sorted from low to high!' ); } if (i == targetRates.length - 1) { require( targetRatesTimestamps[i] < endTime, 'All target rate timestamps should be before endTime!' ); } require(targetRates[i] > 0, 'All target rates must be above 0!'); } } /** * @dev Returns current rate and index for rate in targetRates array. * Does not update target rate index, use checkForNewRateAndUpdate() to * update, */ function getCurrentRate() public view returns (uint256, uint256) { for ( uint256 i = currentTargetRateIndex + 1; i < targetRatesTimestamps.length; i++ ) { if (now < targetRatesTimestamps[i]) { return (targetRates[i - 1], i - 1); } } return ( targetRates[targetRatesTimestamps.length - 1], targetRatesTimestamps.length - 1 ); } /** * @dev Check for new valid rate and update. Automatically called when * purchasing tokens. */ function checkForNewRateAndUpdate() public { (, uint256 targetRateIndex) = getCurrentRate(); // ignore first value if (targetRateIndex > currentTargetRateIndex) { currentTargetRateIndex = targetRateIndex; } } /** * @dev finalizes crowdsale */ function finalization() internal { uint256 remainingTokens = isMinting ? crowdsaleCap.sub(tokensSold) : tokenOnSale.balanceOf(address(this)); if (remainingTokens > 0) { sendPurchasedTokens(address(wallet), remainingTokens); } if (isMinting) { tokenOnSale.transferOwnership(tokenOwnerAfterSale); } super.finalization(); } /** * @dev Get whitelist address. * @return The whitelist address. */ function getWhitelistAddress() external view returns (address) { return address(whitelist); } /** * @dev Get starToken address. * @return The starToken address. */ function getStarTokenAddress() external view returns (address) { return address(starToken); } /** * @dev Get wallet address. * @return The wallet address. */ function getWalletAddress() external view returns (address) { return address(wallet); } /** * @dev Get starEthRateInterface address. * @return The starEthRateInterface address. */ function getStarEthRateInterfaceAddress() external view returns (address) { return address(starEthRateInterface); } /** * @dev Get tokenOnSale address. * @return The tokenOnSale address. */ function getTokenOnSaleAddress() external view returns (address) { return address(tokenOnSale); } function _forwardAnyFunds() private { // when there is still balance left send to wallet contract uint256 ethBalance = address(this).balance; uint256 starBalance = starToken.balanceOf(address(this)); if (ethBalance > 0) { address(wallet).transfer(ethBalance); } if (starBalance > 0) { starToken.transfer(address(wallet), starBalance); } uint256 ethBalanceWallet = address(wallet).balance; uint256 starBalanceWallet = starToken.balanceOf(address(wallet)); if (ethBalanceWallet > 0) { wallet.splitFunds(); } if (starBalanceWallet > 0) { wallet.splitStarFunds(); } } }
function that allows token purchases with Wei beneficiary Address of the purchaser/ calculate token amount to be created remainder logic
function buyTokensWithWei(address beneficiary) internal { uint256 weiAmount = msg.value; uint256 weiRefund; uint256 ethRate = targetRates[currentTargetRateIndex]; uint256 decimals = uint256(tokenOnSale.decimals()); uint256 tokens = weiAmount .mul(ethRate) if (tokensSold.add(tokens) > crowdsaleCap) { tokens = crowdsaleCap.sub(tokensSold); weiAmount = tokens.mul(1e18).div(ethRate).div(10 ** decimals); weiRefund = msg.value.sub(weiAmount); } ethInvestments[beneficiary] = ethInvestments[beneficiary].add(weiAmount); tokensSold = tokensSold.add(tokens); sendPurchasedTokens(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardsWeiFunds(weiRefund); }
6,484,313
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /* Library for reading and writing primitive types to specific storage slots. Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. This library helps with reading and writing to such slots without the need for inline assembly. The functions in this library return Slot structs that contain a `value` member that can be used to read or write. (Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`.) */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } //Returns an `AddressSlot` with member `value` located at `slot`. function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } // Returns an `BooleanSlot` with member `value` located at `slot`. function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } // Returns an `Bytes32Slot` with member `value` located at `slot`. function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } // Returns an `Uint256Slot` with member `value` located at `slot`. function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
Returns an `BooleanSlot` with member `value` located at `slot`.
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } }
7,240,846
pragma solidity ^0.4.19; contract Wicflight { /* * Potential statuses for the Insurance struct * 0: ongoing * 1: insurance contract resolved normaly and the flight landed before the limit * 2: insurance contract resolved normaly and the flight landed after the limit * 3: insurance contract resolved because cancelled by the user * 4: insurance contract resolved because flight cancelled by the air company * 5: insurance contract resolved because flight redirected * 6: insurance contract resolved because flight diverted */ struct Insurance { // all the infos related to a single insurance bytes32 productId; // ID string of the product linked to this insurance uint limitArrivalTime; // maximum arrival time after which we trigger compensation (timestamp in sec) uint32 premium; // amount of the premium uint32 indemnity; // amount of the indemnity uint8 status; // status of this insurance contract. See comment above for potential values } event InsuranceCreation( // event sent when a new insurance contract is added to this smart contract bytes32 flightId, // <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date> uint32 premium, // amount of the premium paid by the user uint32 indemnity, // amount of the potential indemnity bytes32 productId // ID string of the product linked to this insurance ); /* * Potential statuses for the InsuranceUpdate event * 1: flight landed before the limit * 2: flight landed after the limit * 3: insurance contract cancelled by the user * 4: flight cancelled * 5: flight redirected * 6: flight diverted */ event InsuranceUpdate( // event sent when the situation of a particular insurance contract is resolved bytes32 productId, // id string of the user linked to this account bytes32 flightId, // <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date> uint32 premium, // amount of the premium paid by the user uint32 indemnity, // amount of the potential indemnity uint8 status // new status of the insurance contract. See above comment for potential values ); address creator; // address of the creator of the contract // All the insurances handled by this smart contract are contained in this mapping // key: a string containing the flight number and the timestamp separated by a dot // value: an array of insurance contracts for this flight mapping (bytes32 => Insurance[]) insuranceList; // ------------------------------------------------------------------------------------------ // // MODIFIERS / CONSTRUCTOR // ------------------------------------------------------------------------------------------ // /** * @dev This modifier checks that only the creator of the contract can call this smart contract */ modifier onlyIfCreator { if (msg.sender == creator) _; } /** * @dev Constructor */ function Wicflight() public { creator = msg.sender; } // ------------------------------------------------------------------------------------------ // // INTERNAL FUNCTIONS // ------------------------------------------------------------------------------------------ // function areStringsEqual (bytes32 a, bytes32 b) private pure returns (bool) { // generate a hash for each string and compare them return keccak256(a) == keccak256(b); } // ------------------------------------------------------------------------------------------ // // FUNCTIONS TRIGGERING TRANSACTIONS // ------------------------------------------------------------------------------------------ // /** * @dev Add a new insurance for the given flight * @param flightId <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date> * @param limitArrivalTime Maximum time after which we trigger the compensation (timestamp in sec) * @param premium Amount of premium paid by the client * @param indemnity Amount (potentialy) perceived by the client * @param productId ID string of product linked to the insurance */ function addNewInsurance( bytes32 flightId, uint limitArrivalTime, uint32 premium, uint32 indemnity, bytes32 productId) public onlyIfCreator { Insurance memory insuranceToAdd; insuranceToAdd.limitArrivalTime = limitArrivalTime; insuranceToAdd.premium = premium; insuranceToAdd.indemnity = indemnity; insuranceToAdd.productId = productId; insuranceToAdd.status = 0; insuranceList[flightId].push(insuranceToAdd); // send an event about the creation of this insurance contract InsuranceCreation(flightId, premium, indemnity, productId); } /** * @dev Update the status of a flight * @param flightId <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date> * @param actualArrivalTime The actual arrival time of the flight (timestamp in sec) */ function updateFlightStatus( bytes32 flightId, uint actualArrivalTime) public onlyIfCreator { uint8 newStatus = 1; // go through the list of all insurances related to the given flight for (uint i = 0; i < insuranceList[flightId].length; i++) { // we check this contract is still ongoing before updating it if (insuranceList[flightId][i].status == 0) { newStatus = 1; // if the actual arrival time is over the limit the user wanted, // we trigger the indemnity, which means status = 2 if (actualArrivalTime > insuranceList[flightId][i].limitArrivalTime) { newStatus = 2; } // update the status of the insurance contract insuranceList[flightId][i].status = newStatus; // send an event about this update for each insurance InsuranceUpdate( insuranceList[flightId][i].productId, flightId, insuranceList[flightId][i].premium, insuranceList[flightId][i].indemnity, newStatus ); } } } /** * @dev Manually resolve an insurance contract * @param flightId <carrier_code><flight_number>.<timestamp_in_sec_of_departure_date> * @param newStatusId ID of the resolution status for this insurance contract * @param productId ID string of the product linked to the insurance */ function manualInsuranceResolution( bytes32 flightId, uint8 newStatusId, bytes32 productId) public onlyIfCreator { // go through the list of all insurances related to the given flight for (uint i = 0; i < insuranceList[flightId].length; i++) { // look for the insurance contract with the correct ID number if (areStringsEqual(insuranceList[flightId][i].productId, productId)) { // we check this contract is still ongoing before updating it if (insuranceList[flightId][i].status == 0) { // change the status of the insurance contract to the specified one insuranceList[flightId][i].status = newStatusId; // send an event about this update InsuranceUpdate( productId, flightId, insuranceList[flightId][i].premium, insuranceList[flightId][i].indemnity, newStatusId ); return; } } } } function getInsurancesCount(bytes32 flightId) public view onlyIfCreator returns (uint) { return insuranceList[flightId].length; } function getInsurance(bytes32 flightId, uint index) public view onlyIfCreator returns (bytes32, uint, uint32, uint32, uint8) { Insurance memory ins = insuranceList[flightId][index]; return (ins.productId, ins.limitArrivalTime, ins.premium, ins.indemnity, ins.status); } }
we check this contract is still ongoing before updating it if the actual arrival time is over the limit the user wanted, we trigger the indemnity, which means status = 2
function addNewInsurance( bytes32 flightId, uint limitArrivalTime, uint32 premium, uint32 indemnity, bytes32 productId) public } function updateFlightStatus( bytes32 flightId, uint actualArrivalTime) public for (uint i = 0; i < insuranceList[flightId].length; i++) { if (insuranceList[flightId][i].status == 0) { newStatus = 1; if (actualArrivalTime > insuranceList[flightId][i].limitArrivalTime) { newStatus = 2; } insuranceList[flightId][i].productId, flightId, insuranceList[flightId][i].premium, insuranceList[flightId][i].indemnity, newStatus ); } }
6,862,954
pragma solidity ^0.4.18; library ECCMath { /// @dev Modular inverse of a (mod p) using euclid. /// "a" and "p" must be co-prime. /// @param a The number. /// @param p The mmodulus. /// @return x such that ax = 1 (mod p) function invmod(uint a, uint p) internal pure returns (uint) { require(a != 0 && a != p && p != 0); if (a > p) a = a % p; int t1; int t2 = 1; uint r1 = p; uint r2 = a; uint q; while (r2 != 0) { q = r1 / r2; (t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2); } if (t1 < 0) return (p - uint(- t1)); return uint(t1); } /// @dev Modular exponentiation, b^e % m /// @param b The base. /// @param e The exponent. /// @param m The modulus. /// @return x such that x = b**e (mod m) function expmod(uint b, uint e, uint m) internal constant returns (uint r) { if (b == 0) return 0; if (e == 0) return 1; require(m != 0); r = 1; uint bit = 2 ** 255; bit = bit; assembly { loop : jumpi(end, iszero(bit)) r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, bit)))), m) r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, div(bit, 2))))), m) r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, div(bit, 4))))), m) r := mulmod(mulmod(r, r, m), exp(b, iszero(iszero(and(e, div(bit, 8))))), m) bit := div(bit, 16) jump(loop) end : } } /// @dev Converts a point (Px, Py, Pz) expressed in Jacobian coordinates to (Px", Py", 1). /// Mutates P. /// @param P The point. /// @param zInv The modular inverse of "Pz". /// @param z2Inv The square of zInv /// @param prime The prime modulus. /// @return (Px", Py", 1) function toZ1(uint[3] memory P, uint zInv, uint z2Inv, uint prime) internal pure { P[0] = mulmod(P[0], z2Inv, prime); P[1] = mulmod(P[1], mulmod(zInv, z2Inv, prime), prime); P[2] = 1; } /// @dev See _toZ1(uint[3], uint, uint). /// Warning: Computes a modular inverse. /// @param PJ The point. /// @param prime The prime modulus. /// @return (Px", Py", 1) function toZ1(uint[3] PJ, uint prime) internal pure { uint zInv = invmod(PJ[2], prime); uint zInv2 = mulmod(zInv, zInv, prime); PJ[0] = mulmod(PJ[0], zInv2, prime); PJ[1] = mulmod(PJ[1], mulmod(zInv, zInv2, prime), prime); PJ[2] = 1; } }
See _toZ1(uint[3], uint, uint). Warning: Computes a modular inverse. PJ The point. prime The prime modulus. return (Px", Py", 1)
function toZ1(uint[3] PJ, uint prime) internal pure { uint zInv = invmod(PJ[2], prime); uint zInv2 = mulmod(zInv, zInv, prime); PJ[0] = mulmod(PJ[0], zInv2, prime); PJ[1] = mulmod(PJ[1], mulmod(zInv, zInv2, prime), prime); PJ[2] = 1; }
12,737,310
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; contract ERC20SubToken { // TODO add natspec, currently blocked by solidity compiler issue event Transfer(address indexed from, address indexed to, uint256 value); // TODO add natspec, currently blocked by solidity compiler issue event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice A descriptive name for the tokens /// @return name of the tokens function name() public view returns (string memory) { return _name; } /// @notice An abbreviated name for the tokens /// @return symbol of the tokens function symbol() public view returns (string memory) { return _symbol; } /// @notice the tokenId in ERC20Group /// @return the tokenId in ERC20Group function groupTokenId() external view returns (uint256) { return _index; } /// @notice the ERC20Group address /// @return the address of the group function groupAddress() external view returns (address) { return address(_group); } function totalSupply() external view returns (uint256) { return _group.supplyOf(_index); } function balanceOf(address who) external view returns (uint256) { return _group.balanceOf(who, _index); } function decimals() external pure returns (uint8) { return uint8(0); } function transfer(address to, uint256 amount) external returns (bool success) { _transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) external returns (bool success) { if (msg.sender != from && !_group.isAuthorizedToTransfer(from, msg.sender)) { uint256 allowance = _mAllowed[from][msg.sender]; if (allowance != ~uint256(0)) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) require(allowance >= amount, "NOT_AUTHOIZED_ALLOWANCE"); _mAllowed[from][msg.sender] = allowance - amount; } } _transfer(from, to, amount); return true; } function approve(address spender, uint256 amount) external returns (bool success) { _approveFor(msg.sender, spender, amount); return true; } function approveFor( address from, address spender, uint256 amount ) external returns (bool success) { require(msg.sender == from || _group.isAuthorizedToApprove(msg.sender), "NOT_AUTHORIZED"); _approveFor(from, spender, amount); return true; } function emitTransferEvent( address from, address to, uint256 amount ) external { require(msg.sender == address(_group), "NOT_AUTHORIZED_GROUP_ONLY"); emit Transfer(from, to, amount); } // /////////////////// INTERNAL //////////////////////// function _approveFor( address owner, address spender, uint256 amount ) internal { require(owner != address(0) && spender != address(0), "INVALID_FROM_OR_SPENDER"); _mAllowed[owner][spender] = amount; emit Approval(owner, spender, amount); } function allowance(address owner, address spender) external view returns (uint256 remaining) { return _mAllowed[owner][spender]; } function _transfer( address from, address to, uint256 amount ) internal { _group.singleTransferFrom(from, to, _index, amount); } // ///////////////////// UTILITIES /////////////////////// using SafeMathWithRequire for uint256; // //////////////////// CONSTRUCTOR ///////////////////// constructor( ERC20Group group, uint256 index, string memory tokenName, string memory tokenSymbol ) public { _group = group; _index = index; _name = tokenName; _symbol = tokenSymbol; } // ////////////////////// DATA /////////////////////////// ERC20Group internal immutable _group; uint256 internal immutable _index; mapping(address => mapping(address => uint256)) internal _mAllowed; string internal _name; string internal _symbol; } interface CatalystValue { struct GemEvent { uint256[] gemIds; bytes32 blockHash; } function getValues( uint256 catalystId, uint256 seed, GemEvent[] calldata events, uint32 totalNumberOfGemTypes ) external view returns (uint32[] memory values); } contract Admin { address internal _admin; /// @dev emitted when the contract administrator is changed. /// @param oldAdmin address of the previous administrator. /// @param newAdmin address of the new administrator. event AdminChanged(address oldAdmin, address newAdmin); /// @dev gives the current administrator of this contract. /// @return the current administrator of this contract. function getAdmin() external view returns (address) { return _admin; } /// @dev change the administrator to be `newAdmin`. /// @param newAdmin address of the new administrator. function changeAdmin(address newAdmin) external { require(msg.sender == _admin, "only admin can change admin"); emit AdminChanged(_admin, newAdmin); _admin = newAdmin; } modifier onlyAdmin() { require(msg.sender == _admin, "only admin allowed"); _; } } contract MetaTransactionReceiver is Admin { mapping(address => bool) internal _metaTransactionContracts; /// @dev emiited when a meta transaction processor is enabled/disabled /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled); /// @dev Enable or disable the ability of `metaTransactionProcessor` to perform meta-tx (metaTransactionProcessor rights). /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. function setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) public { require(msg.sender == _admin, "only admin can setup metaTransactionProcessors"); _setMetaTransactionProcessor(metaTransactionProcessor, enabled); } function _setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) internal { _metaTransactionContracts[metaTransactionProcessor] = enabled; emit MetaTransactionProcessor(metaTransactionProcessor, enabled); } /// @dev check whether address `who` is given meta-transaction execution rights. /// @param who The address to query. /// @return whether the address has meta-transaction execution rights. function isMetaTransactionProcessor(address who) external view returns (bool) { return _metaTransactionContracts[who]; } } contract SuperOperators is Admin { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external { require(msg.sender == _admin, "only admin is allowed to add super operators"); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } } interface ERC20 { /// @notice emitted when tokens are transfered from one address to another. /// @param from address from which the token are transfered from (zero means tokens are minted). /// @param to destination address which the token are transfered to (zero means tokens are burnt). /// @param value amount of tokens transferred. event Transfer(address indexed from, address indexed to, uint256 value); /// @notice emitted when owner grant transfer rights to another address /// @param owner address allowing its token to be transferred. /// @param spender address allowed to spend on behalf of `owner` /// @param value amount of tokens allowed. event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice return the current total amount of tokens owned by all holders. /// @return supply total number of tokens held. function totalSupply() external view returns (uint256 supply); /// @notice return the number of tokens held by a particular address. /// @param who address being queried. /// @return balance number of token held by that address. function balanceOf(address who) external view returns (uint256 balance); /// @notice transfer tokens to a specific address. /// @param to destination address receiving the tokens. /// @param value number of tokens to transfer. /// @return success whether the transfer succeeded. function transfer(address to, uint256 value) external returns (bool success); /// @notice transfer tokens from one address to another. /// @param from address tokens will be sent from. /// @param to destination address receiving the tokens. /// @param value number of tokens to transfer. /// @return success whether the transfer succeeded. function transferFrom( address from, address to, uint256 value ) external returns (bool success); /// @notice approve an address to spend on your behalf. /// @param spender address entitled to transfer on your behalf. /// @param value amount allowed to be transfered. /// @param success whether the approval succeeded. function approve(address spender, uint256 value) external returns (bool success); /// @notice return the current allowance for a particular owner/spender pair. /// @param owner address allowing spender. /// @param spender address allowed to spend. /// @return amount number of tokens `spender` can spend on behalf of `owner`. function allowance(address owner, address spender) external view returns (uint256 amount); } interface Medianizer { function read() external view returns (bytes32); } library AddressUtils { function toPayable(address _address) internal pure returns (address payable _payable) { return address(uint160(_address)); } function isContract(address addr) internal view returns (bool) { // for accounts without code, i.e. `keccak256('')`: bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; // solium-disable-next-line security/no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != accountHash); } } library BytesUtil { function memcpy( uint256 dest, uint256 src, uint256 len ) internal pure { // 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)) } } function pointerToBytes(uint256 src, uint256 len) internal pure returns (bytes memory) { bytes memory ret = new bytes(len); uint256 retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, src, len); return ret; } function addressToBytes(address a) internal pure returns (bytes memory b) { assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function uint256ToBytes(uint256 a) internal pure returns (bytes memory b) { assembly { let m := mload(0x40) mstore(add(m, 32), a) mstore(0x40, add(m, 64)) b := m } } function doFirstParamEqualsAddress(bytes memory data, address _address) internal pure returns (bool) { if (data.length < (36 + 32)) { return false; } uint256 value; assembly { value := mload(add(data, 36)) } return value == uint256(_address); } function doParamEqualsUInt256( bytes memory data, uint256 i, uint256 value ) internal pure returns (bool) { if (data.length < (36 + (i + 1) * 32)) { return false; } uint256 offset = 36 + i * 32; uint256 valuePresent; assembly { valuePresent := mload(add(data, offset)) } return valuePresent == value; } function overrideFirst32BytesWithAddress(bytes memory data, address _address) internal pure returns (bytes memory) { uint256 dest; assembly { dest := add(data, 48) } // 48 = 32 (offset) + 4 (func sig) + 12 (address is only 20 bytes) bytes memory addressBytes = addressToBytes(_address); uint256 src; assembly { src := add(addressBytes, 32) } memcpy(dest, src, 20); return data; } function overrideFirstTwo32BytesWithAddressAndInt( bytes memory data, address _address, uint256 _value ) internal pure returns (bytes memory) { uint256 dest; uint256 src; assembly { dest := add(data, 48) } // 48 = 32 (offset) + 4 (func sig) + 12 (address is only 20 bytes) bytes memory bbytes = addressToBytes(_address); assembly { src := add(bbytes, 32) } memcpy(dest, src, 20); assembly { dest := add(data, 68) } // 48 = 32 (offset) + 4 (func sig) + 32 (next slot) bbytes = uint256ToBytes(_value); assembly { src := add(bbytes, 32) } memcpy(dest, src, 32); return data; } } library ObjectLib32 { using SafeMathWithRequire for uint256; enum Operations {ADD, SUB, REPLACE} // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param tokenId Object type * @return bin Bin number * @return index ID's index within that bin */ function getTokenBinIndex(uint256 tokenId) internal pure returns (uint256 bin, uint256 index) { bin = (tokenId * TYPES_BITS_SIZE) / 256; index = tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in binBalances * @param binBalances Uint256 containing the balances of objects * @param index Index of the object in the provided bin * @param amount Value to update the type balance * @param operation Which operation to conduct : * Operations.REPLACE : Replace type balance with amount * Operations.ADD : ADD amount to type balance * Operations.SUB : Substract amount from type balance */ function updateTokenBalance( uint256 binBalances, uint256 index, uint256 amount, Operations operation ) internal pure returns (uint256 newBinBalance) { uint256 objectBalance = 0; if (operation == Operations.ADD) { objectBalance = getValueInBin(binBalances, index); newBinBalance = writeValueInBin(binBalances, index, objectBalance.add(amount)); } else if (operation == Operations.SUB) { objectBalance = getValueInBin(binBalances, index); require(objectBalance >= amount, "can't substract more than there is"); newBinBalance = writeValueInBin(binBalances, index, objectBalance.sub(amount)); } else if (operation == Operations.REPLACE) { newBinBalance = writeValueInBin(binBalances, index, amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in binValue at position index * @param binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param index index at which to retrieve value * @return Value at given index in bin */ function getValueInBin(uint256 binValue, uint256 index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (index + 1); return (binValue >> rightShift) & mask; } /** * @dev return the updated binValue after writing amount at index * @param binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param index Index at which to retrieve value * @param amount Value to store at index in bin * @return Value at given index in bin */ function writeValueInBin( uint256 binValue, uint256 index, uint256 amount ) internal pure returns (uint256) { require(amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (index + 1); return (binValue & ~(mask << leftShift)) | (amount << leftShift); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } library SafeMathWithRequire { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; require(c / a == b, "overflow"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "divbyzero"); // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "undeflow"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "overflow"); return c; } } library SigUtil { function recover(bytes32 hash, bytes memory sig) internal pure returns (address recovered) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); recovered = ecrecover(hash, v, r, s); require(recovered != address(0)); } function recoverWithZeroOnFailure(bytes32 hash, bytes memory sig) internal pure returns (address) { if (sig.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes memory) { return abi.encodePacked("\x19Ethereum Signed Message:\n32", hash); } } contract ERC20Group is SuperOperators, MetaTransactionReceiver { uint256 internal constant MAX_UINT256 = ~uint256(0); /// @notice emitted when a new Token is added to the group. /// @param subToken the token added, its id will be its index in the array. event SubToken(ERC20SubToken subToken); /// @notice emitted when `owner` is allowing or disallowing `operator` to transfer tokens on its behalf. /// @param owner the address approving. /// @param operator the address being granted (or revoked) permission to transfer. /// @param approved whether the operator is granted transfer right or not. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Minter(address minter, bool enabled); /// @notice Enable or disable the ability of `minter` to mint tokens /// @param minter address that will be given/removed minter right. /// @param enabled set whether the minter is enabled or disabled. function setMinter(address minter, bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); _setMinter(minter, enabled); } /// @notice check whether address `who` is given minter rights. /// @param who The address to query. /// @return whether the address has minter rights. function isMinter(address who) public view returns (bool) { return _minters[who]; } /// @dev mint more tokens of a specific subToken . /// @param to address receiving the tokens. /// @param id subToken id (also the index at which it was added). /// @param amount of token minted. function mint( address to, uint256 id, uint256 amount ) external { require(_minters[msg.sender], "NOT_AUTHORIZED_MINTER"); (uint256 bin, uint256 index) = id.getTokenBinIndex(); mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; toPack[bin] = toPack[bin].updateTokenBalance(index, amount, ObjectLib32.Operations.ADD); _packedSupplies[bin] = _packedSupplies[bin].updateTokenBalance(index, amount, ObjectLib32.Operations.ADD); _erc20s[id].emitTransferEvent(address(0), to, amount); } /// @dev mint more tokens of a several subToken . /// @param to address receiving the tokens. /// @param ids subToken ids (also the index at which it was added). /// @param amounts for each token minted. function batchMint( address to, uint256[] calldata ids, uint256[] calldata amounts ) external { require(_minters[msg.sender], "NOT_AUTHORIZED_MINTER"); require(ids.length == amounts.length, "INVALID_INCONSISTENT_LENGTH"); _batchMint(to, ids, amounts); } function _batchMint( address to, uint256[] memory ids, uint256[] memory amounts ) internal { uint256 lastBin = MAX_UINT256; uint256 bal = 0; uint256 supply = 0; mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 0) { (uint256 bin, uint256 index) = ids[i].getTokenBinIndex(); if (lastBin == MAX_UINT256) { lastBin = bin; bal = toPack[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); supply = _packedSupplies[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); } else { if (bin != lastBin) { toPack[lastBin] = bal; bal = toPack[bin]; _packedSupplies[lastBin] = supply; supply = _packedSupplies[bin]; lastBin = bin; } bal = bal.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); supply = supply.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); } _erc20s[ids[i]].emitTransferEvent(address(0), to, amounts[i]); } } if (lastBin != MAX_UINT256) { toPack[lastBin] = bal; _packedSupplies[lastBin] = supply; } } /// @notice return the current total supply of a specific subToken. /// @param id subToken id. /// @return supply current total number of tokens. function supplyOf(uint256 id) external view returns (uint256 supply) { (uint256 bin, uint256 index) = id.getTokenBinIndex(); return _packedSupplies[bin].getValueInBin(index); } /// @notice return the balance of a particular owner for a particular subToken. /// @param owner whose balance it is of. /// @param id subToken id. /// @return balance of the owner function balanceOf(address owner, uint256 id) public view returns (uint256 balance) { (uint256 bin, uint256 index) = id.getTokenBinIndex(); return _packedTokenBalance[owner][bin].getValueInBin(index); } /// @notice return the balances of a list of owners / subTokens. /// @param owners list of addresses to which we want to know the balance. /// @param ids list of subTokens's addresses. /// @return balances list of balances for each request. function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory balances) { require(owners.length == ids.length, "INVALID_INCONSISTENT_LENGTH"); balances = new uint256[](ids.length); for (uint256 i = 0; i < ids.length; i++) { balances[i] = balanceOf(owners[i], ids[i]); } } /// @notice transfer a number of subToken from one address to another. /// @param from owner to transfer from. /// @param to destination address that will receive the tokens. /// @param id subToken id. /// @param value amount of tokens to transfer. function singleTransferFrom( address from, address to, uint256 id, uint256 value ) external { require(to != address(0), "INVALID_TO_ZERO_ADDRESS"); ERC20SubToken erc20 = _erc20s[id]; require( from == msg.sender || msg.sender == address(erc20) || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "NOT_AUTHORIZED" ); (uint256 bin, uint256 index) = id.getTokenBinIndex(); mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; fromPack[bin] = fromPack[bin].updateTokenBalance(index, value, ObjectLib32.Operations.SUB); toPack[bin] = toPack[bin].updateTokenBalance(index, value, ObjectLib32.Operations.ADD); erc20.emitTransferEvent(from, to, value); } /// @notice transfer a number of different subTokens from one address to another. /// @param from owner to transfer from. /// @param to destination address that will receive the tokens. /// @param ids list of subToken ids to transfer. /// @param values list of amount for eacg subTokens to transfer. function batchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values ) external { require(ids.length == values.length, "INVALID_INCONSISTENT_LENGTH"); require(to != address(0), "INVALID_TO_ZERO_ADDRESS"); require( from == msg.sender || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender] || _metaTransactionContracts[msg.sender], "NOT_AUTHORIZED" ); _batchTransferFrom(from, to, ids, values); } function _batchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values ) internal { uint256 lastBin = MAX_UINT256; uint256 balFrom; uint256 balTo; mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; for (uint256 i = 0; i < ids.length; i++) { if (values[i] != 0) { (uint256 bin, uint256 index) = ids[i].getTokenBinIndex(); if (lastBin == MAX_UINT256) { lastBin = bin; balFrom = ObjectLib32.updateTokenBalance(fromPack[bin], index, values[i], ObjectLib32.Operations.SUB); balTo = ObjectLib32.updateTokenBalance(toPack[bin], index, values[i], ObjectLib32.Operations.ADD); } else { if (bin != lastBin) { fromPack[lastBin] = balFrom; toPack[lastBin] = balTo; balFrom = fromPack[bin]; balTo = toPack[bin]; lastBin = bin; } balFrom = balFrom.updateTokenBalance(index, values[i], ObjectLib32.Operations.SUB); balTo = balTo.updateTokenBalance(index, values[i], ObjectLib32.Operations.ADD); } ERC20SubToken erc20 = _erc20s[ids[i]]; erc20.emitTransferEvent(from, to, values[i]); } } if (lastBin != MAX_UINT256) { fromPack[lastBin] = balFrom; toPack[lastBin] = balTo; } } /// @notice grant or revoke the ability for an address to transfer token on behalf of another address. /// @param sender address granting/revoking the approval. /// @param operator address being granted/revoked ability to transfer. /// @param approved whether the operator is revoked or approved. function setApprovalForAllFor( address sender, address operator, bool approved ) external { require(msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender], "NOT_AUTHORIZED"); _setApprovalForAll(sender, operator, approved); } /// @notice grant or revoke the ability for an address to transfer token on your behalf. /// @param operator address being granted/revoked ability to transfer. /// @param approved whether the operator is revoked or approved. function setApprovalForAll(address operator, bool approved) external { _setApprovalForAll(msg.sender, operator, approved); } /// @notice return whether an oeprator has the ability to transfer on behalf of another address. /// @param owner address who would have granted the rights. /// @param operator address being given the ability to transfer. /// @return isOperator whether the operator has approval rigths or not. function isApprovedForAll(address owner, address operator) external view returns (bool isOperator) { return _operatorsForAll[owner][operator] || _superOperators[operator]; } function isAuthorizedToTransfer(address owner, address sender) external view returns (bool) { return _metaTransactionContracts[sender] || _superOperators[sender] || _operatorsForAll[owner][sender]; } function isAuthorizedToApprove(address sender) external view returns (bool) { return _metaTransactionContracts[sender] || _superOperators[sender]; } function batchBurnFrom( address from, uint256[] calldata ids, uint256[] calldata amounts ) external { require(from != address(0), "INVALID_FROM_ZERO_ADDRESS"); require( from == msg.sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "NOT_AUTHORIZED" ); _batchBurnFrom(from, ids, amounts); } /// @notice burn token for a specific owner and subToken. /// @param from fron which address the token are burned from. /// @param id subToken id. /// @param value amount of tokens to burn. function burnFrom( address from, uint256 id, uint256 value ) external { require( from == msg.sender || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender] || _metaTransactionContracts[msg.sender], "NOT_AUTHORIZED" ); _burn(from, id, value); } /// @notice burn token for a specific subToken. /// @param id subToken id. /// @param value amount of tokens to burn. function burn(uint256 id, uint256 value) external { _burn(msg.sender, id, value); } // ///////////////// INTERNAL ////////////////////////// function _batchBurnFrom( address from, uint256[] memory ids, uint256[] memory amounts ) internal { uint256 balFrom = 0; uint256 supply = 0; uint256 lastBin = MAX_UINT256; mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 0) { (uint256 bin, uint256 index) = ids[i].getTokenBinIndex(); if (lastBin == MAX_UINT256) { lastBin = bin; balFrom = fromPack[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); supply = _packedSupplies[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); } else { if (bin != lastBin) { fromPack[lastBin] = balFrom; balFrom = fromPack[bin]; _packedSupplies[lastBin] = supply; supply = _packedSupplies[bin]; lastBin = bin; } balFrom = balFrom.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); supply = supply.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); } _erc20s[ids[i]].emitTransferEvent(from, address(0), amounts[i]); } } if (lastBin != MAX_UINT256) { fromPack[lastBin] = balFrom; _packedSupplies[lastBin] = supply; } } function _burn( address from, uint256 id, uint256 value ) internal { ERC20SubToken erc20 = _erc20s[id]; (uint256 bin, uint256 index) = id.getTokenBinIndex(); mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; fromPack[bin] = ObjectLib32.updateTokenBalance(fromPack[bin], index, value, ObjectLib32.Operations.SUB); _packedSupplies[bin] = ObjectLib32.updateTokenBalance(_packedSupplies[bin], index, value, ObjectLib32.Operations.SUB); erc20.emitTransferEvent(from, address(0), value); } function _addSubToken(ERC20SubToken subToken) internal returns (uint256 id) { id = _erc20s.length; require(subToken.groupAddress() == address(this), "INVALID_GROUP"); require(subToken.groupTokenId() == id, "INVALID_ID"); _erc20s.push(subToken); emit SubToken(subToken); } function _setApprovalForAll( address sender, address operator, bool approved ) internal { require(!_superOperators[operator], "INVALID_SUPER_OPERATOR"); _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } function _setMinter(address minter, bool enabled) internal { _minters[minter] = enabled; emit Minter(minter, enabled); } // ///////////////// UTILITIES ///////////////////////// using AddressUtils for address; using ObjectLib32 for ObjectLib32.Operations; using ObjectLib32 for uint256; using SafeMath for uint256; // ////////////////// DATA /////////////////////////////// mapping(uint256 => uint256) internal _packedSupplies; mapping(address => mapping(uint256 => uint256)) internal _packedTokenBalance; mapping(address => mapping(address => bool)) internal _operatorsForAll; ERC20SubToken[] internal _erc20s; mapping(address => bool) internal _minters; // ////////////// CONSTRUCTOR //////////////////////////// struct SubTokenData { string name; string symbol; } constructor( address metaTransactionContract, address admin, address initialMinter ) internal { _admin = admin; _setMetaTransactionProcessor(metaTransactionContract, true); _setMinter(initialMinter, true); } } contract CatalystDataBase is CatalystValue { event CatalystConfiguration(uint256 indexed id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee); function _setMintData(uint256 id, MintData memory data) internal { _data[id] = data; _emitConfiguration(id, data.minQuantity, data.maxQuantity, data.sandMintingFee, data.sandUpdateFee); } function _setValueOverride(uint256 id, CatalystValue valueOverride) internal { _valueOverrides[id] = valueOverride; } function _setConfiguration( uint256 id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) internal { _data[id].minQuantity = minQuantity; _data[id].maxQuantity = maxQuantity; _data[id].sandMintingFee = uint88(sandMintingFee); _data[id].sandUpdateFee = uint88(sandUpdateFee); _emitConfiguration(id, minQuantity, maxQuantity, sandMintingFee, sandUpdateFee); } function _emitConfiguration( uint256 id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) internal { emit CatalystConfiguration(id, minQuantity, maxQuantity, sandMintingFee, sandUpdateFee); } ///@dev compute a random value between min to 25. //. example: 1-25, 6-25, 11-25, 16-25 function _computeValue( uint256 seed, uint256 gemId, bytes32 blockHash, uint256 slotIndex, uint32 min ) internal pure returns (uint32) { return min + uint16(uint256(keccak256(abi.encodePacked(gemId, seed, blockHash, slotIndex))) % (26 - min)); } function getValues( uint256 catalystId, uint256 seed, GemEvent[] calldata events, uint32 totalNumberOfGemTypes ) external override view returns (uint32[] memory values) { CatalystValue valueOverride = _valueOverrides[catalystId]; if (address(valueOverride) != address(0)) { return valueOverride.getValues(catalystId, seed, events, totalNumberOfGemTypes); } values = new uint32[](totalNumberOfGemTypes); uint32 numGems; for (uint256 i = 0; i < events.length; i++) { numGems += uint32(events[i].gemIds.length); } require(numGems <= MAX_UINT32, "TOO_MANY_GEMS"); uint32 minValue = (numGems - 1) * 5 + 1; uint256 numGemsSoFar = 0; for (uint256 i = 0; i < events.length; i++) { numGemsSoFar += events[i].gemIds.length; for (uint256 j = 0; j < events[i].gemIds.length; j++) { uint256 gemId = events[i].gemIds[j]; uint256 slotIndex = numGemsSoFar - events[i].gemIds.length + j; if (values[gemId] == 0) { // first gem : value = roll between ((numGemsSoFar-1)*5+1) and 25 values[gemId] = _computeValue(seed, gemId, events[i].blockHash, slotIndex, (uint32(numGemsSoFar) - 1) * 5 + 1); // bump previous values: if (values[gemId] < minValue) { values[gemId] = minValue; } } else { // further gem, previous roll are overriden with 25 and new roll between 1 and 25 uint32 newRoll = _computeValue(seed, gemId, events[i].blockHash, slotIndex, 1); values[gemId] = (((values[gemId] - 1) / 25) + 1) * 25 + newRoll; } } } } function getMintData(uint256 catalystId) external view returns ( uint16 maxGems, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) { maxGems = _data[catalystId].maxGems; minQuantity = _data[catalystId].minQuantity; maxQuantity = _data[catalystId].maxQuantity; sandMintingFee = _data[catalystId].sandMintingFee; sandUpdateFee = _data[catalystId].sandUpdateFee; } struct MintData { uint88 sandMintingFee; uint88 sandUpdateFee; uint16 minQuantity; uint16 maxQuantity; uint16 maxGems; } uint32 internal constant MAX_UINT32 = 2**32 - 1; mapping(uint256 => MintData) internal _data; mapping(uint256 => CatalystValue) internal _valueOverrides; } contract ERC20GroupCatalyst is CatalystDataBase, ERC20Group { /// @dev add Catalyst, if one of the catalyst to be added in the batch need to have a value override, all catalyst added in that batch need to have override /// if this is not desired, they can be added in a separated batch /// if no override are needed, the valueOverrides can be left emopty function addCatalysts( ERC20SubToken[] memory catalysts, MintData[] memory mintData, CatalystValue[] memory valueOverrides ) public { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); require(catalysts.length == mintData.length, "INVALID_INCONSISTENT_LENGTH"); for (uint256 i = 0; i < mintData.length; i++) { uint256 id = _addSubToken(catalysts[i]); _setMintData(id, mintData[i]); if (valueOverrides.length > i) { _setValueOverride(id, valueOverrides[i]); } } } function addCatalyst( ERC20SubToken catalyst, MintData memory mintData, CatalystValue valueOverride ) public { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); uint256 id = _addSubToken(catalyst); _setMintData(id, mintData); _setValueOverride(id, valueOverride); } function setConfiguration( uint256 id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) external { // CatalystMinter hardcode the value for efficiency purpose, so a change here would require a new deployment of CatalystMinter require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); _setConfiguration(id, minQuantity, maxQuantity, sandMintingFee, sandUpdateFee); } constructor( address metaTransactionContract, address admin, address initialMinter ) public ERC20Group(metaTransactionContract, admin, initialMinter) {} } contract ERC20GroupGem is ERC20Group { function addGems(ERC20SubToken[] calldata catalysts) external { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); for (uint256 i = 0; i < catalysts.length; i++) { _addSubToken(catalysts[i]); } } constructor( address metaTransactionContract, address admin, address initialMinter ) public ERC20Group(metaTransactionContract, admin, initialMinter) {} } contract PurchaseValidator is Admin { address private _signingWallet; // A parallel-queue mapping to nonces. mapping(address => mapping(uint128 => uint128)) public queuedNonces; /// @notice Function to get the nonce for a given address and queue ID /// @param _buyer The address of the starterPack purchaser /// @param _queueId The ID of the nonce queue for the given address. /// The default is queueID=0, and the max is queueID=2**128-1 /// @return uint128 representing the requestied nonce function getNonceByBuyer(address _buyer, uint128 _queueId) external view returns (uint128) { return queuedNonces[_buyer][_queueId]; } /// @notice Check if a purchase message is valid /// @param buyer The address paying for the purchase & receiving tokens /// @param catalystIds The catalyst IDs to be purchased /// @param catalystQuantities The quantities of the catalysts to be purchased /// @param gemIds The gem IDs to be purchased /// @param gemQuantities The quantities of the gems to be purchased /// @param nonce The current nonce for the user. This is represented as a /// uint256 value, but is actually 2 packed uint128's (queueId + nonce) /// @param signature A signed message specifying tx details /// @return True if the purchase is valid function isPurchaseValid( address buyer, uint256[] memory catalystIds, uint256[] memory catalystQuantities, uint256[] memory gemIds, uint256[] memory gemQuantities, uint256 nonce, bytes memory signature ) public returns (bool) { require(_checkAndUpdateNonce(buyer, nonce), "INVALID_NONCE"); bytes32 hashedData = keccak256(abi.encodePacked(catalystIds, catalystQuantities, gemIds, gemQuantities, buyer, nonce)); address signer = SigUtil.recover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedData)), signature); return signer == _signingWallet; } /// @notice Get the wallet authorized for signing purchase-messages. /// @return the address of the signing wallet function getSigningWallet() external view returns (address) { return _signingWallet; } /// @notice Update the signing wallet address /// @param newSigningWallet The new address of the signing wallet function updateSigningWallet(address newSigningWallet) external { require(_admin == msg.sender, "SENDER_NOT_ADMIN"); _signingWallet = newSigningWallet; } /// @dev Function for validating the nonce for a user. /// @param _buyer The address for which we want to check the nonce /// @param _packedValue The queueId + nonce, packed together. /// EG: for queueId=42 nonce=7, pass: "0x0000000000000000000000000000002A00000000000000000000000000000007" function _checkAndUpdateNonce(address _buyer, uint256 _packedValue) private returns (bool) { uint128 queueId = uint128(_packedValue / 2**128); uint128 nonce = uint128(_packedValue % 2**128); uint128 currentNonce = queuedNonces[_buyer][queueId]; if (nonce == currentNonce) { queuedNonces[_buyer][queueId] = currentNonce + 1; return true; } return false; } constructor(address initialSigningWallet) public { _signingWallet = initialSigningWallet; } } contract StarterPackV1 is Admin, MetaTransactionReceiver, PurchaseValidator { using SafeMathWithRequire for uint256; uint256 internal constant DAI_PRICE = 55000000000000000; ERC20 internal immutable _sand; Medianizer private immutable _medianizer; ERC20 private immutable _dai; ERC20Group internal immutable _erc20GroupCatalyst; ERC20Group internal immutable _erc20GroupGem; bool _sandEnabled; bool _etherEnabled; bool _daiEnabled; uint256[] private _starterPackPrices; uint256[] private _previousStarterPackPrices; uint256 private _gemPrice; uint256 private _previousGemPrice; // The timestamp of the last pricechange uint256 private _priceChangeTimestamp; address payable internal _wallet; // The delay between calling setPrices() and when the new prices come into effect. // Minimizes the effect of price changes on pending TXs uint256 private _priceChangeDelay = 1 hours; event Purchase(address indexed buyer, Message message, uint256 price, address token, uint256 amountPaid); event SetPrices(uint256[] prices, uint256 gemPrice); struct Message { uint256[] catalystIds; uint256[] catalystQuantities; uint256[] gemIds; uint256[] gemQuantities; uint256 nonce; } // ////////////////////////// Functions //////////////////////// /// @notice Set the wallet receiving the proceeds /// @param newWallet Address of the new receiving wallet function setReceivingWallet(address payable newWallet) external { require(newWallet != address(0), "WALLET_ZERO_ADDRESS"); require(msg.sender == _admin, "NOT_AUTHORIZED"); _wallet = newWallet; } /// @notice Enable / disable DAI payment for StarterPacks /// @param enabled Whether to enable or disable function setDAIEnabled(bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _daiEnabled = enabled; } /// @notice Return whether DAI payments are enabled /// @return Whether DAI payments are enabled function isDAIEnabled() external view returns (bool) { return _daiEnabled; } /// @notice Enable / disable ETH payment for StarterPacks /// @param enabled Whether to enable or disable function setETHEnabled(bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _etherEnabled = enabled; } /// @notice Return whether ETH payments are enabled /// @return Whether ETH payments are enabled function isETHEnabled() external view returns (bool) { return _etherEnabled; } /// @dev Enable / disable the specific SAND payment for StarterPacks /// @param enabled Whether to enable or disable function setSANDEnabled(bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _sandEnabled = enabled; } /// @notice Return whether SAND payments are enabled /// @return Whether SAND payments are enabled function isSANDEnabled() external view returns (bool) { return _sandEnabled; } /// @notice Purchase StarterPacks with SAND /// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender /// @param message A message containing information about the Catalysts and Gems to be purchased /// @param signature A signed message specifying tx details function purchaseWithSand( address buyer, Message calldata message, bytes calldata signature ) external { require(msg.sender == buyer || _metaTransactionContracts[msg.sender], "INVALID_SENDER"); require(_sandEnabled, "SAND_IS_NOT_ENABLED"); require(buyer != address(0), "DESTINATION_ZERO_ADDRESS"); require( isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature), "INVALID_PURCHASE" ); uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities, message.gemQuantities); _handlePurchaseWithERC20(buyer, _wallet, address(_sand), amountInSand); _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities); emit Purchase(buyer, message, amountInSand, address(_sand), amountInSand); } /// @notice Purchase StarterPacks with Ether /// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender /// @param message A message containing information about the Catalysts and Gems to be purchased /// @param signature A signed message specifying tx details function purchaseWithETH( address buyer, Message calldata message, bytes calldata signature ) external payable { require(msg.sender == buyer || _metaTransactionContracts[msg.sender], "INVALID_SENDER"); require(_etherEnabled, "ETHER_IS_NOT_ENABLED"); require(buyer != address(0), "DESTINATION_ZERO_ADDRESS"); require(buyer != address(this), "DESTINATION_STARTERPACKV1_CONTRACT"); require( isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature), "INVALID_PURCHASE" ); uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities, message.gemQuantities); uint256 ETHRequired = getEtherAmountWithSAND(amountInSand); require(msg.value >= ETHRequired, "NOT_ENOUGH_ETHER_SENT"); _wallet.transfer(ETHRequired); _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities); emit Purchase(buyer, message, amountInSand, address(0), ETHRequired); if (msg.value - ETHRequired > 0) { msg.sender.transfer(msg.value - ETHRequired); // refund extra } } /// @notice Purchase StarterPacks with DAI /// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender /// @param message A message containing information about the Catalysts and Gems to be purchased /// @param signature A signed message specifying tx details function purchaseWithDAI( address buyer, Message calldata message, bytes calldata signature ) external { require(msg.sender == buyer || _metaTransactionContracts[msg.sender], "INVALID_SENDER"); require(_daiEnabled, "DAI_IS_NOT_ENABLED"); require(buyer != address(0), "DESTINATION_ZERO_ADDRESS"); require(buyer != address(this), "DESTINATION_STARTERPACKV1_CONTRACT"); require( isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature), "INVALID_PURCHASE" ); uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities, message.gemQuantities); uint256 DAIRequired = amountInSand.mul(DAI_PRICE).div(1000000000000000000); _handlePurchaseWithERC20(buyer, _wallet, address(_dai), DAIRequired); _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities); emit Purchase(buyer, message, amountInSand, address(_dai), DAIRequired); } /// @notice Enables admin to withdraw all remaining tokens /// @param to The destination address for the purchased Catalysts and Gems /// @param catalystIds The IDs of the catalysts to be transferred /// @param gemIds The IDs of the gems to be transferred function withdrawAll( address to, uint256[] calldata catalystIds, uint256[] calldata gemIds ) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); address[] memory catalystAddresses = new address[](catalystIds.length); for (uint256 i = 0; i < catalystIds.length; i++) { catalystAddresses[i] = address(this); } address[] memory gemAddresses = new address[](gemIds.length); for (uint256 i = 0; i < gemIds.length; i++) { gemAddresses[i] = address(this); } uint256[] memory unsoldCatalystQuantities = _erc20GroupCatalyst.balanceOfBatch(catalystAddresses, catalystIds); uint256[] memory unsoldGemQuantities = _erc20GroupGem.balanceOfBatch(gemAddresses, gemIds); _erc20GroupCatalyst.batchTransferFrom(address(this), to, catalystIds, unsoldCatalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), to, gemIds, unsoldGemQuantities); } /// @notice Enables admin to change the prices of the StarterPack bundles /// @param prices Array of new prices that will take effect after a delay period /// @param gemPrice New price for gems that will take effect after a delay period function setPrices(uint256[] calldata prices, uint256 gemPrice) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _previousStarterPackPrices = _starterPackPrices; _starterPackPrices = prices; _previousGemPrice = _gemPrice; _gemPrice = gemPrice; _priceChangeTimestamp = now; emit SetPrices(prices, gemPrice); } /// @notice Get current StarterPack prices /// @return pricesBeforeSwitch Array of prices before price change /// @return pricesAfterSwitch Array of prices after price change /// @return gemPriceBeforeSwitch Gem price before price change /// @return gemPriceAfterSwitch Gem price after price change /// @return switchTime The time the latest price change will take effect, being the time of the price change plus the price change delay function getPrices() external view returns ( uint256[] memory pricesBeforeSwitch, uint256[] memory pricesAfterSwitch, uint256 gemPriceBeforeSwitch, uint256 gemPriceAfterSwitch, uint256 switchTime ) { switchTime = 0; if (_priceChangeTimestamp != 0) { switchTime = _priceChangeTimestamp + _priceChangeDelay; } return (_previousStarterPackPrices, _starterPackPrices, _previousGemPrice, _gemPrice, switchTime); } /// @notice Returns the amount of ETH for a specific amount of SAND /// @param sandAmount An amount of SAND /// @return The amount of ETH function getEtherAmountWithSAND(uint256 sandAmount) public view returns (uint256) { uint256 ethUsdPair = _getEthUsdPair(); return sandAmount.mul(DAI_PRICE).div(ethUsdPair); } // ////////////////////////// Internal //////////////////////// /// @dev Gets the ETHUSD pair from the Medianizer contract /// @return The pair as an uint256 function _getEthUsdPair() internal view returns (uint256) { bytes32 pair = _medianizer.read(); return uint256(pair); } /// @dev Function to calculate the total price in SAND of the StarterPacks to be purchased /// @dev The price of each StarterPack relates to the catalystId /// @param catalystIds Array of catalystIds to be purchase /// @param catalystQuantities Array of quantities of those catalystIds to be purchased /// @return Total price in SAND function _calculateTotalPriceInSand( uint256[] memory catalystIds, uint256[] memory catalystQuantities, uint256[] memory gemQuantities ) internal returns (uint256) { (uint256[] memory prices, uint256 gemPrice) = _priceSelector(); uint256 totalPrice; for (uint256 i = 0; i < catalystIds.length; i++) { uint256 id = catalystIds[i]; uint256 quantity = catalystQuantities[i]; totalPrice += prices[id].mul(quantity); } for (uint256 i = 0; i < gemQuantities.length; i++) { uint256 quantity = gemQuantities[i]; totalPrice += gemPrice.mul(quantity); } return totalPrice; } /// @dev Function to determine whether to use old or new prices /// @return Array of prices function _priceSelector() internal returns (uint256[] memory, uint256) { uint256[] memory prices; uint256 gemPrice; // No price change: if (_priceChangeTimestamp == 0) { prices = _starterPackPrices; gemPrice = _gemPrice; } else { // Price change delay has expired. if (now > _priceChangeTimestamp + 1 hours) { _priceChangeTimestamp = 0; prices = _starterPackPrices; gemPrice = _gemPrice; } else { // Price change has occured: prices = _previousStarterPackPrices; gemPrice = _previousGemPrice; } } return (prices, gemPrice); } /// @dev Function to handle purchase with SAND or DAI function _handlePurchaseWithERC20( address buyer, address payable paymentRecipient, address tokenAddress, uint256 amount ) internal { ERC20 token = ERC20(tokenAddress); uint256 amountForDestination = amount; require(token.transferFrom(buyer, paymentRecipient, amountForDestination), "PAYMENT_TRANSFER_FAILED"); } // /////////////////// CONSTRUCTOR //////////////////// constructor( address starterPackAdmin, address sandContractAddress, address initialMetaTx, address payable initialWalletAddress, address medianizerContractAddress, address daiTokenContractAddress, address erc20GroupCatalystAddress, address erc20GroupGemAddress, address initialSigningWallet, uint256[] memory initialStarterPackPrices, uint256 initialGemPrice ) public PurchaseValidator(initialSigningWallet) { _setMetaTransactionProcessor(initialMetaTx, true); _wallet = initialWalletAddress; _admin = starterPackAdmin; _sand = ERC20(sandContractAddress); _medianizer = Medianizer(medianizerContractAddress); _dai = ERC20(daiTokenContractAddress); _erc20GroupCatalyst = ERC20Group(erc20GroupCatalystAddress); _erc20GroupGem = ERC20Group(erc20GroupGemAddress); _starterPackPrices = initialStarterPackPrices; _previousStarterPackPrices = initialStarterPackPrices; _gemPrice = initialGemPrice; _previousGemPrice = initialGemPrice; _sandEnabled = true; // Sand is enabled by default _etherEnabled = true; // Ether is enabled by default } }
for accounts without code, i.e. `keccak256('')`: solium-disable-next-line security/no-inline-assembly
function isContract(address addr) internal view returns (bool) { bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != accountHash); }
7,353,240
pragma solidity ^0.4.24; import "../medicineaccesscontrol/Roles.sol"; import "../medicineaccesscontrol/DistributorRole.sol"; import "../medicineaccesscontrol/ManufacturerRole.sol"; import "../medicineaccesscontrol/PatientRole.sol"; import "../medicineaccesscontrol/PharmacistRole.sol"; import "../medicinecore/Ownable.sol"; // Define a contract 'Supplychain' contract SupplyChain is PharmacistRole, PatientRole, ManufacturerRole, DistributorRole { // Define 'owner' address owner; // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'medicines' that maps the UPC to an Medicine. mapping (uint => Medicine) medicines; // Define a public mapping 'medicinesHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) medicinesHistory; // Define enum 'State' with the following values: enum State { Made, // 0 Packed, // 1 ForSale, // 2 Sold, // 3 Shipped, // 4 Received, // 5 Purchased // 6 } State constant defaultState = State.Made; // Define a struct 'Medicine' with the following fields: struct Medicine { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Manufacturer, goes on the package, can be verified by the Patient address ownerID; // Metamask-Ethereum address of the current owner as the medicine moves through 8 stages address originManufacturerID; // Metamask-Ethereum address of the Manufacturer string originFactoryName; // Manufacturer Name string originFactoryInformation; // Manufacturer Information string originFactoryLatitude; // Factory Latitude string originFactoryLongitude; // Factory Longitude uint medicineID; // Product ID potentially a combination of upc + sku string medicineNotes; // Product Notes uint medicinePrice; // Product Price State medicineState; // Product State as represented in the enum above address distributorID; // Metamask-Ethereum address of the Distributor address pharmacistID; // Metamask-Ethereum address of the Pharmacist address patientID; // Metamask-Ethereum address of the Patient } // Define 8 events with the same 7 state values and accept 'upc' as input argument event Made(uint upc); event Packed(uint upc); event ForSale(uint upc); event Sold(uint upc); event Shipped(uint upc); event Received(uint upc); event Purchased(uint upc); // Define a modifer that checks to see if msg.sender == owner of the contract modifier onlyOwner() { require(msg.sender == owner); _; } // 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 _upc) { _; uint _price = medicines[_upc].medicinePrice; uint amountToReturn = msg.value - _price; medicines[_upc].patientID.transfer(amountToReturn); } // Define a modifier that checks if an medicine.state of a upc is Made modifier made(uint _upc) { require(medicines[_upc].medicineState == State.Made); _; } // Define a modifier that checks if an medicine.state of a upc is Packed modifier packed(uint _upc) { require(medicines[_upc].medicineState == State.Packed); _; } // Define a modifier that checks if an medicine.state of a upc is ForSale modifier forSale(uint _upc) { require(medicines[_upc].medicineState == State.ForSale); _; } // Define a modifier that checks if an medicine.state of a upc is Sold modifier sold(uint _upc) { require(medicines[_upc].medicineState == State.Sold); _; } // Define a modifier that checks if an medicine.state of a upc is Shipped modifier shipped(uint _upc) { require(medicines[_upc].medicineState == State.Shipped); _; } // Define a modifier that checks if an medicine.state of a upc is Received modifier received(uint _upc) { require(medicines[_upc].medicineState == State.Received); _; } // Define a modifier that checks if an medicine.state of a upc is Purchased modifier purchased(uint _upc) { require(medicines[_upc].medicineState == State.Purchased); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() public payable { owner = msg.sender; sku = 0; upc = 0; } // Define a function 'kill' if required function kill() public { if (msg.sender == owner) { selfdestruct(owner); } } // Define a function 'makeMedicine' that allows a manufacturer to mark a medicine 'Made' function makeMedicine(uint _upc, address _originManufacturerID, string _originFactoryName, string _originFactoryInformation, string _originFactoryLatitude, string _originFactoryLongitude, string _medicineNotes) public onlyManufacturer { // Add the new medicine as part of medicines Medicine memory temp_medicine = Medicine({ sku:sku + 1, upc:_upc, ownerID:_originManufacturerID, originManufacturerID:_originManufacturerID, originFactoryName:_originFactoryName, originFactoryInformation:_originFactoryInformation, originFactoryLatitude:_originFactoryLatitude, originFactoryLongitude:_originFactoryLongitude, medicineID:sku+_upc, medicineNotes:_medicineNotes, medicineState:State.Made, medicinePrice:0, distributorID:0, pharmacistID:0, patientID:0 }); medicines[_upc] = temp_medicine; medicines[_upc].medicineState = State.Made; // uint sku; // Stock Keeping Unit (SKU) // uint upc; // Universal Product Code (UPC), generated by the Manufacturer, goes on the package, can be verified by the Patient // address ownerID; // Metamask-Ethereum address of the current owner as the medicine moves through 8 stages // address originManufacturerID; // Metamask-Ethereum address of the Manufacturer // string originFactoryName; // Manufacturer Name // string originFactoryInformation; // Manufacturer Information // string originFactoryLatitude; // Factory Latitude // string originFactoryLongitude; // Factory Longitude // uint medicineID; // Product ID potentially a combination of upc + sku // string medicineNotes; // Product Notes // uint medicinePrice; // Product Price // State medicineState; // Product State as represented in the enum above // address distributorID; // Metamask-Ethereum address of the Distributor // address pharmacistID; // Metamask-Ethereum address of the Pharmacist // address patientID; // Metamask-Ethereum address of the Patient // Increment sku sku = sku + 1; // Emit the appropriate event emit Made(_upc); } // Define a function 'packMedicine' that allows a manufacturer to mark an medicine 'Packed' function packMedicine(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage made(_upc) // Call modifier to verify caller of this function onlyManufacturer { // Update the appropriate fields medicines[_upc].medicineState = State.Packed; // Emit the appropriate event emit Packed(_upc); } // Define a function 'sellMedicine' that allows a manufacturer to mark an medicine 'ForSale' function sellMedicine(uint _upc, uint _price) public // Call modifier to check if upc has passed previous supply chain stage packed(_upc) // Call modifier to verify caller of this function onlyManufacturer { // Update the appropriate fields medicines[_upc].medicineState = State.ForSale; medicines[_upc].medicinePrice = _price; // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyMedicine' that allows the disributor to mark an medicine 'Sold' // Use the above defined modifiers to check if the medicine is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyMedicine(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(medicines[_upc].medicinePrice) // Call modifer to send any excess ether back to buyer checkValue(_upc) //limit to distributers , no end consumers are allowed to buy from factory. onlyDistributor { // Update the appropriate fields - ownerID, distributorID, medicineState medicines[_upc].medicineState = State.Sold; // Transfer money to manufacturer medicines[_upc].originManufacturerID.transfer(medicines[_upc].medicinePrice); // emit the appropriate event emit Sold(_upc); } // Define a function 'shipMedicine' that allows the distributor to mark an medicine 'Shipped' // Use the above modifers to check if the medicine is sold function shipMedicine(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function onlyManufacturer { //check if the factory is the one making this medicine. require(medicines[_upc].originManufacturerID == msg.sender,"Manufacturers can ship only medicines by them"); // Update the appropriate fields medicines[_upc].medicineState = State.Shipped; // Emit the appropriate event emit Shipped(_upc); } // Define a function 'receiveMedicine' that allows the pharmacist to mark an medicine 'Received' // Use the above modifiers to check if the medicine is shipped function receiveMedicine(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipped(_upc) // Access Control List enforced by calling Smart Contract / DApp { // Update the appropriate fields - ownerID, pharmacistID, medicineState medicines[_upc].medicineState = State.Received; // Emit the appropriate event emit Received(_upc); } // Define a function 'purchaseMedicine' that allows the patient to mark an medicine 'Purchased' // Use the above modifiers to check if the medicine is received function purchaseMedicine(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage received(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyPatient { // Up medicines[_upc].medicineState = State.Shipped; medicines[_upc].medicineState = State.Purchased; // Emit the appropriate event emit Purchased(_upc); } // Define a function 'fetchMedicineBufferOne' that fetches the data function fetchMedicineBufferOne(uint _upc) public view returns ( uint medicineSKU, uint medicineUPC, address ownerID, address originManufacturerID, string originFactoryName, string originFactoryInformation, string originFactoryLatitude // string originFactoryLongitude ) { // Assign values to the 7 parameters return ( medicines[_upc].sku, medicines[_upc].upc, medicines[_upc].ownerID, medicines[_upc].originManufacturerID, medicines[_upc].originFactoryName, medicines[_upc].originFactoryInformation, medicines[_upc].originFactoryLatitude // medicines[_upc].originFactoryLongitude ); } // Define a function 'fetchMedicineBufferTwo' that fetches the data function fetchMedicineBufferTwo(uint _upc) public view returns ( // uint medicineSKU, // uint medicineUPC, // uint medicineID, string originFactoryLongitude, string medicineNotes, uint medicinePrice, State medicineState, address distributorID, address pharmacistID, address patientID ) { // Assign values to the 7 parameters return ( // medicines[_upc].sku, // medicines[_upc].upc, // medicines[_upc].medicineID, medicines[_upc].originFactoryLongitude, medicines[_upc].medicineNotes, medicines[_upc].medicinePrice, medicines[_upc].medicineState, medicines[_upc].distributorID, medicines[_upc].pharmacistID, medicines[_upc].patientID ); } // Define a function 'fetchMedicineBufferThree' that fetches the data function fetchMedicineBufferThree(uint _upc) public view returns ( uint medicineSKU, uint medicineUPC, uint medicineID ) { // Assign values to the 3 parameters return ( medicines[_upc].sku, medicines[_upc].upc, medicines[_upc].medicineID ); } }
Define a function 'kill' if required
function kill() public { if (msg.sender == owner) { selfdestruct(owner); } }
5,495,039
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; import "./BattleRoyale.sol"; import "./AddressArray.sol"; import "./CustomAccessControl.sol"; contract BattleRoyaleArena is CustomAccessControl, VRFConsumerBase { using AddressArray for AddressArray.Addresses; // Chainlink properties bytes32 internal keyHash; uint256 public fee; // Address of primary wallet address payable public walletAddress; // temp mapping for battles in random elimination mechanic mapping(bytes32 => address payable) requestToBattle; // Look into elimination logic and how to maintain state of all NFTs in and out of play AddressArray.Addresses battleQueue; constructor( address _vrfCoordinator, address _linkToken, bytes32 _keyHash, uint256 _fee ) public VRFConsumerBase(_vrfCoordinator, _linkToken) { keyHash = _keyHash; fee = _fee; // Set to Chainlink fee for network, Rinkeby and Kovan is 0.1 LINK and MAINNET is 2 LINK walletAddress = payable(owner()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * Fallback function to receive ETH */ receive() external payable {} /* * Method to withdraw ETH */ function withdraw(uint256 amount) external onlyAdmin { uint256 balance = address(this).balance; require(amount <= balance); if (walletAddress != address(0)) { payable(walletAddress).transfer(amount); } else { msg.sender.transfer(amount); } } /* * Get Current ETH Balance from contract */ function getCurrentBalance() external onlySupport view returns (uint256) { uint256 balance = address(this).balance; return balance; } /* * Method to withdraw LINK */ function withdrawLink(uint256 amount) external onlyAdmin returns (bool) { uint256 balance = LINK.balanceOf(address(this)); require(amount <= balance); if (walletAddress != address(0)) { return LINK.transfer(address(walletAddress), amount); } else { return LINK.transfer(msg.sender, amount); } } /* * Get Current LINK Balance from contract */ function getCurrentLinkBalance() external onlySupport view returns (uint256) { return LINK.balanceOf(address(this)); } /* ===== Battle Royale Arena Methods ===== */ function addToBattleQueue(address payable _nftAddress) external payable onlySupport returns(bool) { return battleQueue.push(_nftAddress); } function getBattleQueue() external view returns (address payable[] memory) { return battleQueue.getAll(); } function isContractInQueue(address payable _contract) external view returns (bool) { return battleQueue.exists(_contract); } function removeFromQueue(address payable nftAddress) external onlySupport payable returns(address payable[] memory) { battleQueue.remove(nftAddress); return battleQueue.getAll(); } function setWalletAddress(address payable _wallet) external onlyOwner payable { walletAddress = _wallet; } function bytesToAddress(bytes memory bys) internal pure returns (address payable addr) { assembly { addr := mload(add(bys,20)) } } /* * addressToBytes * @param {[type]} address [description] * @return {[type]} [description] */ function addressToBytes(address payable a) internal pure returns (bytes memory b) { return abi.encodePacked(a); } /* ========================== * CHAINLINK METHODS * ========================== */ /* === Keeper Network === */ /* * Check upkeep will excute upkeep when intervals hit 0 */ function checkUpkeep(bytes calldata checkData) external returns( bool upkeepNeeded, bytes memory performData ) { for (uint i = 0; i < battleQueue.size(); i++) { address payable nftAddress = battleQueue.atIndex(i); BattleRoyale battle = BattleRoyale(nftAddress); uint256 timestamp = battle.timestamp(); uint256 intervalTime = battle.intervalTime(); if (battle.getBattleStateInt() == 1 && block.timestamp >= timestamp + (intervalTime * 1 minutes)) { return (true, addressToBytes(nftAddress)); } } return (false, checkData); } /* * Perform Upkeep execute random elimination */ function performUpkeep(bytes calldata performData) onlySupport external { address payable nftAddress = bytesToAddress(performData); // Adjust queue battleQueue.remove(nftAddress); battleQueue.push(nftAddress); // execute upkeep executeBattle(nftAddress); } /* === Verifiable Random Function === */ function executeBattle(address payable _nftAddress) internal returns (bytes32) { BattleRoyale battle = BattleRoyale(_nftAddress); require(LINK.balanceOf(address(this)) >= fee); require(battle.getBattleStateInt() == 1); require(battle.getInPlaySize() > 1); bytes32 requestId = requestRandomness(keyHash, fee); requestToBattle[requestId] = _nftAddress; return requestId; } function fulfillRandomness(bytes32 _requestId, uint256 _randomNumber) internal override { address payable nftAddress = requestToBattle[_requestId]; BattleRoyale battle = BattleRoyale(nftAddress); battle.executeRandomElimination(_randomNumber); delete requestToBattle[_requestId]; } // Delegate callback method called when game has ended function gameDidEnd(address payable _address) external payable { BattleRoyale battle = BattleRoyale(_address); uint256 balance = battle.getCurrentBalance(); battle.withdraw(balance); battleQueue.remove(_address); } function executeEliminationByQueue() external onlySupport returns(bool) { for (uint i = 0; i < battleQueue.size(); ++i) { address payable nftAddress = battleQueue.atIndex(i); return executeElimination(nftAddress); } return false; } function executeElimination(address payable _nftAddress) public onlySupport returns(bool) { require(battleQueue.exists(_nftAddress)); BattleRoyale battle = BattleRoyale(_nftAddress); uint256 timestamp = battle.timestamp(); uint256 intervalTime = battle.intervalTime(); if (battle.getBattleStateInt() == 1 && block.timestamp >= timestamp + (intervalTime * 1 minutes)) { // execute upkeep battleQueue.remove(_nftAddress); battleQueue.push(_nftAddress); executeBattle(_nftAddress); return true; } return false; } /* ======== Battle Royale Methods ======== */ function getInPlayOnNFT(address payable _nft) external view onlySupport returns (uint256[] memory) { BattleRoyale battle = BattleRoyale(_nft); return battle.getInPlay(); } function getOutOfPlayOnNFT(address payable _nft) external view onlySupport returns (uint256[] memory) { BattleRoyale battle = BattleRoyale(_nft); return battle.getOutOfPlay(); } function setIntervalTimeOnNFT(address payable _nft, uint256 _intervalTime) external payable onlySupport returns (uint256) { BattleRoyale battle = BattleRoyale(_nft); return battle.setIntervalTime(_intervalTime); } function setPriceOnNFT(address payable _nft, uint256 _price) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setPrice(_price); } function NFTAutoStartOn(address payable _nft, bool _autoStart) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.autoStartOn(_autoStart); } function NFTAutoPayoutOn(address payable _nft, bool _autoPayout) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.autoPayoutOn(_autoPayout); } function setFeeRateOnNFT(address payable _nft, uint256 _feeRate) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setFeeRate(_feeRate); } function setUnitsPerTransactionOnNFT(address payable _nft,uint256 _units) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setUnitsPerTransaction(_units); } function setMaxSupplyOnNFT(address payable _nft, uint256 _supply) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setMaxSupply(_supply); } function setDefaultTokenURIOnNFT(address payable _nft, string memory _tokenUri) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setDefaultTokenURI(_tokenUri); } function setPrizeTokenURIOnNFT(address payable _nft, string memory _tokenUri) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setPrizeTokenURI(_tokenUri); } function setArtistOnNFT(address payable _nft, address payable _artist) external onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.setArtist(_artist); } function beginBattleOnNFT(address payable _nft) external onlySupport { BattleRoyale battle = BattleRoyale(_nft); battle.beginBattle(); } function executePayoutOnNFT(address payable _nft) public onlySupport payable { BattleRoyale battle = BattleRoyale(_nft); battle.executePayout(); } /* ======== Battle Royale Methods ======== */ function transferContractOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); revokeAccessRole(payable(owner())); grantSupportAccess(newOwner); transferOwnership(newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./vendor/SafeMathChainlink.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @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].add(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) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "./ERC721Tradable.sol"; import "./AddressArray.sol"; import "./Uint256Array.sol"; import "./BattleRoyaleArena.sol"; contract BattleRoyale is ERC721Tradable { using AddressArray for AddressArray.Addresses; using Uint256Array for Uint256Array.Uint256s; // Structure of token data on chain struct NFTRoyale { bool inPlay; uint256 placement; } // Maximum number of mintable tokens uint256 public maxSupply = 0; // current purchasable units per transaction uint256 public unitsPerTransaction; // Prize token URI to be set to winner string public prizeTokenURI; // Prize token URI to be set to winner string public defaultTokenURI; // time in minutes uint256 public intervalTime; // timestamp of last elimination uint256 public timestamp; // initial price per token uint256 public price; // Current game state enum BATTLE_STATE { STANDBY, RUNNING, ENDED } BATTLE_STATE public battleState; // Look into elimination logic and how to maintain state of all NFTs in and out of play Uint256Array.Uint256s inPlay; Uint256Array.Uint256s outOfPlay; // Array of purchaser addresses AddressArray.Addresses purchasers; // Temp mapping for NFTs awaiting game execution mapping(uint256 => NFTRoyale) public nftRoyales; // set to true when wanting the game to start automatically once sales hit max supply bool public autoStart; // set to true when wanting the game to start automatically once sales hit max supply bool public autoPayout; // Address of the artist address payable public artist; address payable public delegate; // Set rate uint256 public feeRate; /* * constructor */ constructor( string memory _name, string memory _symbol, uint256 _price, uint256 _units, uint256 _supply, bool _autoStart, bool _autoPayout, address payable _delegate ) public ERC721Tradable( _name, _symbol, 'https://ipfs.io/ipfs/' ) { battleState = BATTLE_STATE.STANDBY; intervalTime = 30; price = _price; unitsPerTransaction = _units; maxSupply = _supply; autoStart = _autoStart; autoPayout = _autoPayout; delegate = _delegate; } /* * Mint NFTs */ function purchase(uint256 units) external payable { require(price > 0); require(battleState == BATTLE_STATE.STANDBY); require(maxSupply > 0 && totalSupply() < maxSupply); require(units <= maxSupply - totalSupply()); require(units > 0 && units <= unitsPerTransaction); require(bytes(defaultTokenURI).length > 0); require(msg.value >= (price * units)); require(purchasers.getIndex(msg.sender) < 0, "Only 1 purchase per account."); // add buyer address to list purchasers.push(msg.sender); for (uint256 i = 0; i < units; i++) { uint256 tokenId = mintTo(msg.sender); _setTokenURI(tokenId, defaultTokenURI); inPlay.push(tokenId); nftRoyales[tokenId] = NFTRoyale({ inPlay: true, placement: 0 }); } // Begin battle if max supply has been reached if (maxSupply == totalSupply() && autoStart) { startBattle(); } } /* * Burn method * @param {[type]} uint256 [description] * @return {[type]} [description] */ function burn(uint256 _tokenId) public virtual { require(msg.sender == ownerOf(_tokenId) || msg.sender == delegate || msg.sender == owner()); delete nftRoyales[_tokenId]; inPlay.remove(_tokenId); _burn(_tokenId); } /* ========================== * BATTLE ROYALE METHODS * ========================== */ /* * Method to withdraw ETH */ function withdraw(uint256 amount) external override virtual { require(msg.sender == delegate || msg.sender == owner()); uint256 balance = address(this).balance; require(amount <= balance); if (delegate != address(0)) { payable(delegate).transfer(amount); } else { msg.sender.transfer(amount); } } /* * Get Current ETH Balance from contract */ function getCurrentBalance() external override returns (uint256) { require(msg.sender == delegate || msg.sender == owner()); uint256 balance = address(this).balance; return balance; } /** * get all token IDs In Play * @return {[type]} array of IDs */ function getInPlay() external view returns (uint256[] memory) { return inPlay.getAll(); } function getInPlaySize() external view returns (uint256) { return inPlay.size(); } /** * get all token IDs out of Play * @return {[type]} array of IDs */ function getOutOfPlay() external view returns (uint256[] memory) { return outOfPlay.getAll(); } /* * Set Interval * @param {[type]} uint256 [description] */ function setIntervalTime(uint256 _intervalTime) external payable returns (uint256) { require(msg.sender == delegate || msg.sender == owner()); intervalTime = _intervalTime; } /* * isTokenInPlay - check if owner is still in player */ function isTokenInPlay(uint256 _tokenId) external view returns (bool) { return nftRoyales[_tokenId].inPlay; } /* * getTokenPlacement */ function getTokenPlacement(uint256 _tokenId) external view returns (uint256) { return nftRoyales[_tokenId].placement; } /* * set currentPrice */ function setPrice(uint256 _price) external payable { require(msg.sender == delegate || msg.sender == owner()); price = _price; } /* * Toggle auto-start on or off */ function autoStartOn(bool _autoStart) external payable { require(msg.sender == delegate || msg.sender == owner()); autoStart = _autoStart; } /* * Toggle auto-start on or off */ function autoPayoutOn(bool _autoPayout) external payable { require(msg.sender == delegate || msg.sender == owner()); autoPayout = _autoPayout; } /* * Set Fee Rate - aggreed rate the contract takes from the artist for initial sale */ function setFeeRate(uint256 _feeRate) external payable { require(msg.sender == delegate || msg.sender == owner()); feeRate = _feeRate; } /* * setUnitsPerTransaction */ function setUnitsPerTransaction(uint256 _units) external payable { require(msg.sender == delegate || msg.sender == owner()); unitsPerTransaction = _units; } /* * setMaxSupply */ function setMaxSupply(uint256 supply) external payable { require(msg.sender == delegate || msg.sender == owner()); maxSupply = supply; } /* * setdefaultTokenURI method to set the meta-data uri for the winning token to * be set later when game has ended * @param string IPFS meta-data uri */ function setDefaultTokenURI(string memory _tokenUri) external payable { require(msg.sender == delegate || msg.sender == owner()); defaultTokenURI = _tokenUri; } /* * setPrizeTokenURI method to set the meta-data uri for the winning token to * be set later when game has ended * @param string IPFS meta-data uri */ function setPrizeTokenURI(string memory _tokenUri) external payable { require(msg.sender == delegate || msg.sender == owner()); prizeTokenURI = _tokenUri; } /* * set artist */ function setArtist(address payable _artist) external payable { require(msg.sender == delegate || msg.sender == owner()); artist = _artist; } /* * Delegate notifier method */ function notifyGameEnded() internal { BattleRoyaleArena arena = BattleRoyaleArena(payable(delegate)); arena.gameDidEnd(address(this)); } /* * getBattleState * @return current state string of the game to web app */ function getBattleState() external view returns (string memory) { if (battleState == BATTLE_STATE.STANDBY) { return 'STANDBY'; } if (battleState == BATTLE_STATE.RUNNING) { return 'RUNNING'; } if (battleState == BATTLE_STATE.ENDED) { return 'ENDED'; } } function getBattleStateInt() external view returns (uint256) { return uint256(battleState); } /* * beginBattle * Method to call to begin the game battle */ function beginBattle() external { require(msg.sender == delegate || msg.sender == owner()); startBattle(); } function startBattle() internal { require(bytes(prizeTokenURI).length > 0 && inPlay.size() > 1); battleState = BATTLE_STATE.RUNNING; // Set to current clock timestamp = block.timestamp; } /* * executeRandomElimination trigger elimination using Chainlink VRF */ function executeRandomElimination(uint256 _randomNumber) external payable { require(msg.sender == delegate || msg.sender == owner()); require(battleState == BATTLE_STATE.RUNNING); require(inPlay.size() > 1); uint256 i = _randomNumber % inPlay.size(); uint256 tokenId = inPlay.atIndex(i); outOfPlay.push(tokenId); inPlay.remove(tokenId); NFTRoyale storage royale = nftRoyales[tokenId]; royale.inPlay = false; royale.placement = inPlay.size() + 1; timestamp = block.timestamp; if (inPlay.size() == 1) { battleState = BATTLE_STATE.ENDED; royale = nftRoyales[tokenId]; royale.inPlay = false; royale.placement = inPlay.size(); tokenId = inPlay.atIndex(0); _setTokenURI(tokenId, prizeTokenURI); notifyGameEnded(); if (autoPayout) { executeAutoPayout(); } } } /* * calculateFee * Uses basis points to calculate fee */ function calculateFee(uint amount) internal returns (uint) { require((amount / 1000) * 1000 == amount, 'amount is too small'); return amount * feeRate / 10000; } /* * payout artist */ function executePayout() public payable { require(msg.sender == delegate || msg.sender == owner()); executeAutoPayout(); } function executeAutoPayout() internal { uint256 balance = address(this).balance; if (artist != address(0) && (balance / 1000) * 1000 == balance && feeRate > 0) { uint256 payout = balance - calculateFee(balance); artist.transfer(payout); } balance = address(this).balance; payable(delegate).transfer(balance); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; library AddressArray { using AddressArray for Addresses; struct Addresses { address payable[] _items; } /** * @notice push an address to the array * @dev if the address already exists, it will not be added again * @param self Storage array containing address type variables * @param element the element to add in the array */ function push(Addresses storage self, address payable element) internal returns (bool) { if (!exists(self, element)) { self._items.push(element); return true; } return false; } /** * @notice remove an address from the array * @dev finds the element, swaps it with the last element, and then deletes it; * returns a boolean whether the element was found and deleted * @param self Storage array containing address type variables * @param element the element to remove from the array */ function remove(Addresses storage self, address payable element) internal returns (bool) { int256 i = getIndex(self, element); if (i >= 0) { return removeByIndex(self, uint256(i)); } return false; } /** * @notice get the address at a specific index from array * @dev revert if the index is out of bounds * @param self Storage array containing address type variables * @param index the index in the array */ function atIndex(Addresses storage self, uint256 index) internal view returns (address payable) { require(index < size(self), "the index is out of bounds"); return self._items[index]; } /** * @notice get the size of the array * @param self Storage array containing address type variables */ function size(Addresses storage self) internal view returns (uint256) { return self._items.length; } /** * @notice check if an element exist in the array * @param self Storage array containing address type variables * @param element the element to check if it exists in the array */ function exists(Addresses storage self, address payable element) internal view returns (bool) { return getIndex(self, element) >= 0; } /** * @notice get the array * @param self Storage array containing address type variables */ function getAll(Addresses storage self) internal view returns(address payable[] memory) { return self._items; } /* * @notice get index of address * @param self Storage array containing address type variables * @param element the element to get index in array */ function getIndex(Addresses storage self, address payable element) internal view returns(int256) { for (uint256 i = 0; i < size(self); i++){ if(self._items[i] == element) { return int256(i); } uint256 j = size(self) - 1 - i; if (self._items[j] == element) { return int256(j); } if (i >= j) { break; } } return -1; } /* * @notice get index of address * @param self Storage array containing address type variables * @param i index of element to remove */ function removeByIndex(Addresses storage self, uint256 i) internal returns (bool) { if (i < size(self)) { uint last = size(self) - 1; if (i < last) { self._items[i] = self._items[last]; } self._items.pop(); return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./AddressArray.sol"; contract CustomAccessControl is AccessControl, Ownable { using AddressArray for AddressArray.Addresses; // Array of purchaser addresses AddressArray.Addresses users; bytes32 public constant SUPPORT_ROLE = keccak256("DEFAULT_SUPPORT_ROLE"); function supportLevelAccess(address account) public view returns (bool) { return hasRole(SUPPORT_ROLE, account) || adminLevelAccess(account); } function adminLevelAccess(address account) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, account) || account == owner(); } function superAdminLevelAccess(address account) public view returns (bool) { return account == owner(); } function grantSupportAccess(address payable account) public onlyOwner { if (users.exists(account)) { revokeAccessRole(account); } else { users.push(account); } grantRole(SUPPORT_ROLE, account); } function grantAdminAccess(address payable account) public onlyOwner { if (users.exists(account)) { revokeAccessRole(account); } else { users.push(account); } grantRole(DEFAULT_ADMIN_ROLE, account); } function revokeAccessRole(address payable account) public payable onlyOwner returns (bool) { if (hasRole(DEFAULT_ADMIN_ROLE, account)) { revokeRole(DEFAULT_ADMIN_ROLE, account); users.remove(account); return true; } else if (hasRole(SUPPORT_ROLE, account)) { users.remove(account); revokeRole(SUPPORT_ROLE, account); return true; } return false; } function getAddressRole(address account) external returns (string memory) { if (hasRole(DEFAULT_ADMIN_ROLE, account)) { return 'ADMIN_ROLE'; } else if (hasRole(SUPPORT_ROLE, account)) { return 'SUPPORT_ROLE'; } return 'UNASSIGNED'; } function getAllAccessAddresses() external view onlyOwner returns(address payable[] memory) { return users.getAll(); } function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } /** * @dev Throws if called by any account other than the owner. */ modifier onlySupport() { require(supportLevelAccess(_msgSender()), "Caller does not have access"); _; } modifier onlyAdmin() { require(adminLevelAccess(_msgSender()), "Caller does not have access"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.6.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ contract ERC721Tradable is ERC721, Ownable { using Strings for string; using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor( string memory _name, string memory _symbol, string memory _baseURI ) public ERC721(_name, _symbol) { _setBaseURI(_baseURI); } /** * Fallback function to receive ETH */ receive() external payable {} /* * Method to withdraw ETH */ function withdraw(uint256 amount) external virtual onlyOwner { uint256 balance = address(this).balance; require(amount <= balance); msg.sender.transfer(amount); } /* * Get Current ETH Balance from contract */ function getCurrentBalance() external virtual onlyOwner returns (uint256) { uint256 balance = address(this).balance; return balance; } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) internal returns (uint256) { _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _safeMint(_to, newTokenId); return newTokenId; } /* * setTokenURI * @param {[type]} uint256 [description] * @param {[type]} string [description] */ function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner payable { _setTokenURI(_tokenId, _tokenURI); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; library Uint256Array { using Uint256Array for Uint256s; struct Uint256s { uint256[] _items; } /** * @notice push an uint256 to the array * @dev if the uint256 already exists, it will not be added again * @param self Storage array containing uint256 type variables * @param element the element to add in the array */ function push(Uint256s storage self, uint256 element) internal returns (bool) { if (!exists(self, element)) { self._items.push(element); return true; } return false; } /** * @notice remove a uint256 from the array * @dev finds the element, swaps it with the last element, and then deletes it; * returns a boolean whether the element was found and deleted * @param self Storage array containing uint256 type variables * @param element the element to remove from the array */ function remove(Uint256s storage self, uint256 element) internal returns (bool) { int256 i = getIndex(self, element); if (i >= 0) { return removeByIndex(self, uint256(i)); } return false; } /** * @notice get the uint256 at a specific index from array * @dev revert if the index is out of bounds * @param self Storage array containing uint256 type variables * @param index the index in the array */ function atIndex(Uint256s storage self, uint256 index) internal view returns (uint256) { require(index < size(self), "the index is out of bounds"); return self._items[index]; } /** * @notice get the size of the array * @param self Storage array containing uint256 type variables */ function size(Uint256s storage self) internal view returns (uint256) { return self._items.length; } /** * @notice check if an element exist in the array * @param self Storage array containing uint256 type variables * @param element the element to check if it exists in the array */ function exists(Uint256s storage self, uint256 element) internal view returns (bool) { return getIndex(self, element) >= 0; } /** * @notice get the array * @param self Storage array containing uint256 type variables */ function getAll(Uint256s storage self) internal view returns(uint256[] memory) { return self._items; } /* * @notice get index of uint256 * @param self Storage array containing uint256 type variables * @param element the element to get index in array */ function getIndex(Uint256s storage self, uint256 element) internal view returns(int256) { for (uint256 i = 0; i < size(self); i++){ if(self._items[i] == element) { return int256(i); } uint256 j = size(self) - 1 - i; if (self._items[j] == element) { return int256(j); } if (i >= j) { break; } } return -1; } /* * @notice get index of uint256 * @param self Storage array containing uint256 type variables * @param i index of element to remove */ function removeByIndex(Uint256s storage self, uint256 i) internal returns (bool) { if (i < size(self)) { uint last = size(self) - 1; if (i < last) { self._items[i] = self._items[last]; } self._items.pop(); return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // 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 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.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()); } } }
beginBattle Method to call to begin the game battle/
function beginBattle() external { require(msg.sender == delegate || msg.sender == owner()); startBattle(); }
1,384,360
./partial_match/1/0xD1C833b46266CcF6060e90B69161FCEe9C66E826/sources/src/NightWatch.sol
Get the frames of the specified token. tokenId Id of the token to get its frames. return frames Array of binary integers that specifies frames. Revert if the token data is not found. Get the token data. Iterate over the frames and set them.
function getFrames( uint256 tokenId ) external view returns (uint256[15] memory frames) { if (_tokenData.length <= tokenId) revert TokenDataNotFound(); uint24 data = _tokenData[tokenId]; for (uint256 i; i < 15; ) { frames[i] = data & (1 << i) > 0 ? 1 : 0; unchecked { ++i; } } } MERGE LOGIC
15,944,912
./partial_match/42/0x5C389323Aa3D197031c45737d6d254C8B8F79B45/sources/DebtIssuanceModule.sol
If any manager fees mints Sets to the defined feeRecipient. If protocol fee is enabled mints Sets to protocol feeRecipient./
function _resolveFees(ISetToken _setToken, uint256 managerFee, uint256 protocolFee) internal { if (managerFee > 0) { _setToken.mint(issuanceSettings[_setToken].feeRecipient, managerFee); if (protocolFee > 0) { _setToken.mint(controller.feeRecipient(), protocolFee); } } }
3,444,170
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.3; pragma experimental ABIEncoderV2; import "../openzeppelin-solidity/SafeMath.sol"; import "../storage/BZxStorage.sol"; import "../BZxVault.sol"; import "../oracle/OracleInterface.sol"; import "./MathFunctions.sol"; contract MiscFunctions is BZxStorage, MathFunctions { using SafeMath for uint256; function _payInterestForOracle( LenderInterest memory oracleInterest, address lender, address oracleAddress, address interestTokenAddress, bool sendToOracle) internal returns (uint256) { address oracleRef = oracleAddresses[oracleAddress]; uint256 interestOwedNow; if (oracleInterest.interestOwedPerDay > 0 && oracleInterest.interestPaidDate > 0 && interestTokenAddress != address(0)) { interestOwedNow = block.timestamp.sub(oracleInterest.interestPaidDate).mul(oracleInterest.interestOwedPerDay).div(86400); if (interestOwedNow > tokenInterestOwed[lender][interestTokenAddress]) interestOwedNow = tokenInterestOwed[lender][interestTokenAddress]; if (interestOwedNow != 0) { oracleInterest.interestPaid = oracleInterest.interestPaid.add(interestOwedNow); tokenInterestOwed[lender][interestTokenAddress] = tokenInterestOwed[lender][interestTokenAddress].sub(interestOwedNow); if (sendToOracle) { // send the interest to the oracle for further processing if (!BZxVault(vaultContract).withdrawToken( interestTokenAddress, oracleRef, interestOwedNow )) { revert("_payInterestForOracle: BZxVault.withdrawToken failed"); } // calls the oracle to signal processing of the interest (ie: paying the lender, retaining fees) if (!OracleInterface(oracleRef).didPayInterestByLender( lender, interestTokenAddress, interestOwedNow, gasUsed // initial used gas, collected in modifier )) { revert("_payInterestForOracle: OracleInterface.didPayInterestByLender failed"); } } else { if (!BZxVault(vaultContract).withdrawToken( interestTokenAddress, lender, interestOwedNow )) { revert("_payInterestForOracle: BZxVault.withdrawToken interest failed"); } } } } oracleInterest.interestPaidDate = block.timestamp; lenderOracleInterest[lender][oracleAddress][interestTokenAddress] = oracleInterest; return interestOwedNow; } /// @dev Calculates the sum of values already filled and cancelled for a given loanOrder. /// @param loanOrderHash A unique hash representing the loan order. /// @return Sum of values already filled and cancelled. function _getUnavailableLoanTokenAmount( bytes32 loanOrderHash) internal view returns (uint256) { uint256 unavailableAmount = orderFilledAmounts[loanOrderHash].add(orderCancelledAmounts[loanOrderHash]); return (orders[loanOrderHash].loanTokenAmount >= unavailableAmount ? unavailableAmount : orders[loanOrderHash].loanTokenAmount); } function _getCollateralRequired( address loanTokenAddress, address collateralTokenAddress, address oracleAddress, uint256 loanTokenAmountFilled, uint256 marginAmount) internal view returns (uint256 collateralTokenAmount) { if (loanTokenAddress == collateralTokenAddress) { collateralTokenAmount = loanTokenAmountFilled .mul(marginAmount) .div(10**20); } else { (uint256 sourceToDestRate, uint256 sourceToDestPrecision,) = OracleInterface(oracleAddresses[oracleAddress]).getTradeData( collateralTokenAddress, loanTokenAddress, MAX_UINT // get best rate ); collateralTokenAmount = loanTokenAmountFilled .mul(sourceToDestPrecision) .div(sourceToDestRate) .mul(marginAmount) .div(10**20); } if (collateralTokenAmount == 0) { revert("_getCollateralRequired: collateralTokenAmount == 0"); } } function _tradePositionWithOracle( LoanOrder memory loanOrder, LoanPosition memory loanPosition, address destTokenAddress, uint256 maxDestTokenAmount, bool ensureHealthy) internal returns (uint256 destTokenAmountReceived, uint256 positionTokenAmountUsed) { if (loanPosition.positionTokenAmountFilled > 0) { // transfer the current position token to the Oracle contract if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, oracleAddresses[loanOrder.oracleAddress], loanPosition.positionTokenAmountFilled)) { revert("MiscFunctions::_tradePositionWithOracle: BZxVault.withdrawToken failed"); } (destTokenAmountReceived, positionTokenAmountUsed) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).tradePosition( loanOrder, loanPosition, destTokenAddress, maxDestTokenAmount, ensureHealthy ); } } function _removeLoanOrder( bytes32 loanOrderHash, address addr) internal { if (orderListIndex[loanOrderHash][addr].isSet) { assert(orderList[addr].length > 0); uint256 index = orderListIndex[loanOrderHash][addr].index; if (orderList[addr].length > 1) { // replace order in list with last order in array orderList[addr][index] = orderList[addr][orderList[addr].length - 1]; // update the position of this replacement orderListIndex[orderList[addr][index]][addr].index = index; } // trim array and clear storage orderList[addr].length--; orderListIndex[loanOrderHash][addr].index = 0; orderListIndex[loanOrderHash][addr].isSet = false; } } }
transfer the current position token to the Oracle contract
function _tradePositionWithOracle( LoanOrder memory loanOrder, LoanPosition memory loanPosition, address destTokenAddress, uint256 maxDestTokenAmount, bool ensureHealthy) internal returns (uint256 destTokenAmountReceived, uint256 positionTokenAmountUsed) { if (loanPosition.positionTokenAmountFilled > 0) { if (!BZxVault(vaultContract).withdrawToken( loanPosition.positionTokenAddressFilled, oracleAddresses[loanOrder.oracleAddress], loanPosition.positionTokenAmountFilled)) { revert("MiscFunctions::_tradePositionWithOracle: BZxVault.withdrawToken failed"); } (destTokenAmountReceived, positionTokenAmountUsed) = OracleInterface(oracleAddresses[loanOrder.oracleAddress]).tradePosition( loanOrder, loanPosition, destTokenAddress, maxDestTokenAmount, ensureHealthy ); } }
6,434,754
pragma solidity ^0.4.18; contract DelegateERC20 { function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address who) public view returns (uint256); function delegateTransfer(address to, uint256 value, address origSender) public returns (bool); function delegateAllowance(address owner, address spender) public view returns (uint256); function delegateTransferFrom(address from, address to, uint256 value, address origSender) public returns (bool); function delegateApprove(address spender, uint256 value, address origSender) public returns (bool); function delegateIncreaseApproval(address spender, uint addedValue, address origSender) public returns (bool); function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) public returns (bool); } contract Ownable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function transferOwnership(address newOwner) public; } contract Pausable is Ownable { event Pause(); event Unpause(); function pause() public; function unpause() public; } contract CanReclaimToken is Ownable { function reclaimToken(ERC20Basic token) external; } contract Claimable is Ownable { function transferOwnership(address newOwner) public; function claimOwnership() public; } contract AddressList is Claimable { event ChangeWhiteList(address indexed to, bool onList); function changeList(address _to, bool _onList) public; } contract HasNoContracts is Ownable { function reclaimContract(address contractAddr) external; } contract HasNoEther is Ownable { function() external; function reclaimEther() external; } contract HasNoTokens is CanReclaimToken { function tokenFallback(address from_, uint256 value_, bytes data_) external; } contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } contract AllowanceSheet is Claimable { function addAllowance(address tokenHolder, address spender, uint256 value) public; function subAllowance(address tokenHolder, address spender, uint256 value) public; function setAllowance(address tokenHolder, address spender, uint256 value) public; } contract BalanceSheet is Claimable { function addBalance(address addr, uint256 value) public; function subBalance(address addr, uint256 value) public; function setBalance(address addr, uint256 value) public; } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic, Claimable { function setBalanceSheet(address sheet) external; function totalSupply() public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal; function balanceOf(address _owner) public view returns (uint256 balance); } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public; } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { } contract StandardToken is ERC20, BasicToken { function setAllowanceSheet(address sheet) external; function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function transferAllArgsYesAllowance(address _from, address _to, uint256 _value, address spender) internal; function approve(address _spender, uint256 _value) public returns (bool); function approveAllArgs(address _spender, uint256 _value, address _tokenHolder) internal; function allowance(address _owner, address _spender) public view returns (uint256); function increaseApproval(address _spender, uint _addedValue) public returns (bool); function increaseApprovalAllArgs(address _spender, uint _addedValue, address tokenHolder) internal; function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool); function decreaseApprovalAllArgs(address _spender, uint _subtractedValue, address tokenHolder) internal; } contract CanDelegate is StandardToken { event DelegatedTo(address indexed newContract); function delegateToNewContract(DelegateERC20 newContract) public; function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function balanceOf(address who) public view returns (uint256); function approve(address spender, uint256 value) public returns (bool); function allowance(address _owner, address spender) public view returns (uint256); function totalSupply() public view returns (uint256); function increaseApproval(address spender, uint addedValue) public returns (bool); function decreaseApproval(address spender, uint subtractedValue) public returns (bool); } contract StandardDelegate is StandardToken, DelegateERC20 { function setDelegatedFrom(address addr) public; function delegateTotalSupply() public view returns (uint256); function delegateBalanceOf(address who) public view returns (uint256); function delegateTransfer(address to, uint256 value, address origSender) public returns (bool); function delegateAllowance(address owner, address spender) public view returns (uint256); function delegateTransferFrom(address from, address to, uint256 value, address origSender) public returns (bool); function delegateApprove(address spender, uint256 value, address origSender) public returns (bool); function delegateIncreaseApproval(address spender, uint addedValue, address origSender) public returns (bool); function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) public returns (bool); } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function increaseApproval(address _spender, uint _addedValue) public returns (bool success); function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success); } contract TrueUSD is StandardDelegate, PausableToken, BurnableToken, NoOwner, CanDelegate { event ChangeBurnBoundsEvent(uint256 newMin, uint256 newMax); event Mint(address indexed to, uint256 amount); event WipedAccount(address indexed account, uint256 balance); function setLists(AddressList _canReceiveMintWhiteList, AddressList _canBurnWhiteList, AddressList _blackList, AddressList _noFeesList) public; function changeName(string _name, string _symbol) public; function burn(uint256 _value) public; function mint(address _to, uint256 _amount) public; function changeBurnBounds(uint newMin, uint newMax) public; function transferAllArgsNoAllowance(address _from, address _to, uint256 _value) internal; function wipeBlacklistedAccount(address account) public; function payStakingFee(address payer, uint256 value, uint80 numerator, uint80 denominator, uint256 flatRate, address otherParticipant) private returns (uint256); function changeStakingFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public; function changeStaker(address newStaker) public; } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library NewSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Cash311 * @dev The main contract of the project. */ /** * @title Cash311 * @dev https://311.cash/; */ contract Cash311 { // Connecting SafeMath for safe calculations. // Подключает библиотеку безопасных вычислений к контракту. using NewSafeMath for uint; // A variable for address of the owner; // Переменная для хранения адреса владельца контракта; address owner; // A variable for address of the ERC20 token; // Переменная для хранения адреса токена ERC20; TrueUSD public token = TrueUSD(0x8dd5fbce2f6a956c3022ba3663759011dd51e73e); // A variable for decimals of the token; // Переменная для количества знаков после запятой у токена; uint private decimals = 10**18; // A variable for storing deposits of investors. // Переменная для хранения записей о сумме инвестиций инвесторов. mapping (address => uint) deposit; uint deposits; // A variable for storing amount of withdrawn money of investors. // Переменная для хранения записей о сумме снятых средств. mapping (address => uint) withdrawn; // A variable for storing reference point to count available money to withdraw. // Переменная для хранения времени отчета для инвесторов. mapping (address => uint) lastTimeWithdraw; // RefSystem mapping (address => uint) referals1; mapping (address => uint) referals2; mapping (address => uint) referals3; mapping (address => uint) referals1m; mapping (address => uint) referals2m; mapping (address => uint) referals3m; mapping (address => address) referers; mapping (address => bool) refIsSet; mapping (address => uint) refBonus; // A constructor function for the contract. It used single time as contract is deployed. // Единоразовая функция вызываемая при деплое контракта. function Cash311() public { // Sets an owner for the contract; // Устанавливает владельца контракта; owner = msg.sender; } // A function for transferring ownership of the contract (available only for the owner). // Функция для переноса права владения контракта (доступна только для владельца). function transferOwnership(address _newOwner) external { require(msg.sender == owner); require(_newOwner != address(0)); owner = _newOwner; } // RefSystem function bytesToAddress1(bytes source) internal pure returns(address parsedReferer) { assembly { parsedReferer := mload(add(source,0x14)) } return parsedReferer; } // A function for getting key info for investors. // Функция для вызова ключевой информации для инвестора. function getInfo(address _address) public view returns(uint Deposit, uint Withdrawn, uint AmountToWithdraw, uint Bonuses) { // 1) Amount of invested tokens; // 1) Сумма вложенных токенов; Deposit = deposit[_address].div(decimals); // 2) Amount of withdrawn tokens; // 3) Сумма снятых средств; Withdrawn = withdrawn[_address].div(decimals); // Amount of tokens which is available to withdraw. // Formula without SafeMath: ((Current Time - Reference Point) / 1 period)) * (Deposit * 0.0311) // Расчет количества токенов доступных к выводу; // Формула без библиотеки безопасных вычислений: ((Текущее время - Отчетное время) / 1 period)) * (Сумма депозита * 0.0311) uint _a = (block.timestamp.sub(lastTimeWithdraw[_address])).div(1 days).mul(deposit[_address].mul(311).div(10000)); AmountToWithdraw = _a.div(decimals); // RefSystem Bonuses = refBonus[_address].div(decimals); } // RefSystem function getRefInfo(address _address) public view returns(uint Referals1, uint Referals1m, uint Referals2, uint Referals2m, uint Referals3, uint Referals3m) { Referals1 = referals1[_address]; Referals1m = referals1m[_address].div(decimals); Referals2 = referals2[_address]; Referals2m = referals2m[_address].div(decimals); Referals3 = referals3[_address]; Referals3m = referals3m[_address].div(decimals); } function getNumber() public view returns(uint) { return deposits; } function getTime(address _address) public view returns(uint Hours, uint Minutes) { Hours = (lastTimeWithdraw[_address] % 1 days) / 1 hours; Minutes = (lastTimeWithdraw[_address] % 1 days) % 1 hours / 1 minutes; } // A "fallback" function. It is automatically being called when anybody sends ETH to the contract. Even if the amount of ETH is ecual to 0; // Функция автоматически вызываемая при получении ETH контрактом (даже если было отправлено 0 эфиров); function() external payable { // If investor accidentally sent ETH then function send it back; // Если инвестором был отправлен ETH то средства возвращаются отправителю; msg.sender.transfer(msg.value); // If the value of sent ETH is equal to 0 then function executes special algorithm: // 1) Gets amount of intended deposit (approved tokens). // 2) If there are no approved tokens then function "withdraw" is called for investors; // Если было отправлено 0 эфиров то исполняется следующий алгоритм: // 1) Заправшивается количество токенов для инвестирования (кол-во одобренных к выводу токенов). // 2) Если одобрены токенов нет, для действующих инвесторов вызывается функция инвестирования (после этого действие функции прекращается); uint _approvedTokens = token.allowance(msg.sender, address(this)); if (_approvedTokens == 0 && deposit[msg.sender] > 0) { withdraw(); return; // If there are some approved tokens to invest then function "invest" is called; // Если были одобрены токены то вызывается функция инвестирования (после этого действие функции прекращается); } else { if (msg.data.length == 20) { address referer = bytesToAddress1(bytes(msg.data)); if (referer != msg.sender) { invest(referer); return; } } invest(0x0); return; } } // RefSystem function refSystem(uint _value, address _referer) internal { refBonus[_referer] = refBonus[_referer].add(_value.div(40)); referals1m[_referer] = referals1m[_referer].add(_value); if (refIsSet[_referer]) { address ref2 = referers[_referer]; refBonus[ref2] = refBonus[ref2].add(_value.div(50)); referals2m[ref2] = referals2m[ref2].add(_value); if (refIsSet[referers[_referer]]) { address ref3 = referers[referers[_referer]]; refBonus[ref3] = refBonus[ref3].add(_value.mul(3).div(200)); referals3m[ref3] = referals3m[ref3].add(_value); } } } // RefSystem function setRef(uint _value, address referer) internal { if (deposit[referer] > 0) { referers[msg.sender] = referer; refIsSet[msg.sender] = true; referals1[referer] = referals1[referer].add(1); if (refIsSet[referer]) { referals2[referers[referer]] = referals2[referers[referer]].add(1); if (refIsSet[referers[referer]]) { referals3[referers[referers[referer]]] = referals3[referers[referers[referer]]].add(1); } } refBonus[msg.sender] = refBonus[msg.sender].add(_value.div(50)); refSystem(_value, referer); } } // A function which accepts tokens of investors. // Функция для перевода токенов на контракт. function invest(address _referer) public { // Gets amount of deposit (approved tokens); // Заправшивает количество токенов для инвестирования (кол-во одобренных к выводу токенов); uint _value = token.allowance(msg.sender, address(this)); // Transfers approved ERC20 tokens from investors address; // Переводит одобренные к выводу токены ERC20 на данный контракт; token.transferFrom(msg.sender, address(this), _value); // Transfers a fee to the owner of the contract. The fee is 10% of the deposit (or Deposit / 10) // Начисляет комиссию владельцу (10%); refBonus[owner] = refBonus[owner].add(_value.div(10)); // The special algorithm for investors who increases their deposits: // Специальный алгоритм для инвесторов увеличивающих их вклад; if (deposit[msg.sender] > 0) { // Amount of tokens which is available to withdraw. // Formula without SafeMath: ((Current Time - Reference Point) / 1 period)) * (Deposit * 0.0311) // Расчет количества токенов доступных к выводу; // Формула без библиотеки безопасных вычислений: ((Текущее время - Отчетное время) / 1 period)) * (Сумма депозита * 0.0311) uint amountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender])).div(1 days).mul(deposit[msg.sender].mul(311).div(10000)); // The additional algorithm for investors who need to withdraw available dividends: // Дополнительный алгоритм для инвесторов которые имеют средства к снятию; if (amountToWithdraw != 0) { // Increasing the withdrawn tokens by the investor. // Увеличение количества выведенных средств инвестором; withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw); // Transferring available dividends to the investor. // Перевод доступных к выводу средств на кошелек инвестора; token.transfer(msg.sender, amountToWithdraw); // RefSystem uint _bonus = refBonus[msg.sender]; if (_bonus != 0) { refBonus[msg.sender] = 0; token.transfer(msg.sender, _bonus); withdrawn[msg.sender] = withdrawn[msg.sender].add(_bonus); } } // Setting the reference point to the current time. // Установка нового отчетного времени для инвестора; lastTimeWithdraw[msg.sender] = block.timestamp; // Increasing of the deposit of the investor. // Увеличение Суммы депозита инвестора; deposit[msg.sender] = deposit[msg.sender].add(_value); // End of the function for investors who increases their deposits. // Конец функции для инвесторов увеличивающих свои депозиты; // RefSystem if (refIsSet[msg.sender]) { refSystem(_value, referers[msg.sender]); } else if (_referer != 0x0 && _referer != msg.sender) { setRef(_value, _referer); } return; } // The algorithm for new investors: // Setting the reference point to the current time. // Алгоритм для новых инвесторов: // Установка нового отчетного времени для инвестора; lastTimeWithdraw[msg.sender] = block.timestamp; // Storing the amount of the deposit for new investors. // Установка суммы внесенного депозита; deposit[msg.sender] = (_value); deposits += 1; // RefSystem if (refIsSet[msg.sender]) { refSystem(_value, referers[msg.sender]); } else if (_referer != 0x0 && _referer != msg.sender) { setRef(_value, _referer); } } // A function for getting available dividends of the investor. // Функция для вывода средств доступных к снятию; function withdraw() public { // Amount of tokens which is available to withdraw. // Formula without SafeMath: ((Current Time - Reference Point) / 1 period)) * (Deposit * 0.0311) // Расчет количества токенов доступных к выводу; // Формула без библиотеки безопасных вычислений: ((Текущее время - Отчетное время) / 1 period)) * (Сумма депозита * 0.0311) uint amountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender])).div(1 days).mul(deposit[msg.sender].mul(311).div(10000)); // Reverting the whole function for investors who got nothing to withdraw yet. // В случае если к выводу нет средств то функция отменяется; if (amountToWithdraw == 0) { revert(); } // Increasing the withdrawn tokens by the investor. // Увеличение количества выведенных средств инвестором; withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw); // Updating the reference point. // Formula without SafeMath: Current Time - ((Current Time - Previous Reference Point) % 1 period) // Обновление отчетного времени инвестора; // Формула без библиотеки безопасных вычислений: Текущее время - ((Текущее время - Предыдущее отчетное время) % 1 period) lastTimeWithdraw[msg.sender] = block.timestamp.sub((block.timestamp.sub(lastTimeWithdraw[msg.sender])).mod(1 days)); // Transferring the available dividends to the investor. // Перевод выведенных средств; token.transfer(msg.sender, amountToWithdraw); // RefSystem uint _bonus = refBonus[msg.sender]; if (_bonus != 0) { refBonus[msg.sender] = 0; token.transfer(msg.sender, _bonus); withdrawn[msg.sender] = withdrawn[msg.sender].add(_bonus); } } }
A function which accepts tokens of investors. Функция для перевода токенов на контракт. Gets amount of deposit (approved tokens); Заправшивает количество токенов для инвестирования (кол-во одобренных к выводу токенов); Transfers approved ERC20 tokens from investors address; Переводит одобренные к выводу токены ERC20 на данный контракт; Transfers a fee to the owner of the contract. The fee is 10% of the deposit (or Deposit / 10) Начисляет комиссию владельцу (10%); The special algorithm for investors who increases their deposits: Специальный алгоритм для инвесторов увеличивающих их вклад; Amount of tokens which is available to withdraw. Formula without SafeMath: ((Current Time - Reference Point) / 1 period)) (Deposit 0.0311) Расчет количества токенов доступных к выводу; Формула без библиотеки безопасных вычислений: ((Текущее время - Отчетное время) / 1 period)) (Сумма депозита 0.0311) The additional algorithm for investors who need to withdraw available dividends: Дополнительный алгоритм для инвесторов которые имеют средства к снятию; Increasing the withdrawn tokens by the investor. Увеличение количества выведенных средств инвестором; Transferring available dividends to the investor. Перевод доступных к выводу средств на кошелек инвестора; RefSystem RefSystem RefSystem
function invest(address _referer) public { uint _value = token.allowance(msg.sender, address(this)); token.transferFrom(msg.sender, address(this), _value); refBonus[owner] = refBonus[owner].add(_value.div(10)); if (deposit[msg.sender] > 0) { uint amountToWithdraw = (block.timestamp.sub(lastTimeWithdraw[msg.sender])).div(1 days).mul(deposit[msg.sender].mul(311).div(10000)); if (amountToWithdraw != 0) { withdrawn[msg.sender] = withdrawn[msg.sender].add(amountToWithdraw); token.transfer(msg.sender, amountToWithdraw); uint _bonus = refBonus[msg.sender]; if (_bonus != 0) { refBonus[msg.sender] = 0; token.transfer(msg.sender, _bonus); withdrawn[msg.sender] = withdrawn[msg.sender].add(_bonus); } } if (refIsSet[msg.sender]) { refSystem(_value, referers[msg.sender]); setRef(_value, _referer); } return; } deposits += 1; if (refIsSet[msg.sender]) { refSystem(_value, referers[msg.sender]); setRef(_value, _referer); } }
6,680,256
// 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 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: UNLICENSED /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity 0.8.11; library BytesLib { function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../../../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IHarvestPool { function rewardToken() external view returns (address); function lpToken() external view returns (address); function duration() external view returns (uint256); function periodFinish() external view returns (uint256); function rewardRate() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function stake(uint256 amountWei) external; // `balanceOf` would give the amount staked. // As this is 1 to 1, this is also the holder's share function balanceOf(address holder) external view returns (uint256); // total shares & total lpTokens staked function totalSupply() external view returns (uint256); function withdraw(uint256 amountWei) external; function exit() external; // get claimed rewards function earned(address holder) external view returns (uint256); // claim rewards function getReward() external; // notify function notifyRewardAmount(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IHarvestVault { function underlyingBalanceInVault() external view returns (uint256); function underlyingBalanceWithInvestment() external view returns (uint256); // function store() external view returns (address); function governance() external view returns (address); function controller() external view returns (address); function underlying() external view returns (address); function strategy() external view returns (address); function setStrategy(address _strategy) external; function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external; function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdrawAll() external; function withdraw(uint256 numberOfShares) external; function getPricePerFullShare() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256); // hard work should be callable only by the controller (by the hard worker) or by governance function doHardWork() external; function totalSupply() external view returns (uint256); function balanceOf(address user) external view returns (uint256); function approve(address user, uint256 amount) external returns (bool); function underlyingUnit() external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IV2SwapRouter.sol'; import './IV3SwapRouter.sol'; /// @title Router token swapping functionality interface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V2 interface IV2SwapRouter { /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @param amountIn The amount of token to swap /// @param amountOutMin The minimum amount of output that must be received /// @param path The ordered list of tokens to swap through /// @param to The recipient address /// @return amountOut The amount of the received token function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to ) external payable returns (uint256 amountOut); /// @notice Swaps as little as possible of one token for an exact amount of another token /// @param amountOut The amount of token to swap for /// @param amountInMax The maximum amount of input that the caller will pay /// @param path The ordered list of tokens to swap through /// @param to The recipient address /// @return amountIn The amount of token to pay function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to ) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IV3SwapRouter{ struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// that may remain in the router after the swap. /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// that may remain in the router after the swap. /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; import "./ISwapData.sol"; interface IBaseStrategy { function underlying() external view returns (IERC20); function getStrategyBalance() external view returns (uint128); function getStrategyUnderlyingWithRewards() external view returns(uint128); function process(uint256[] calldata, bool, SwapData[] calldata) external; function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128); function processDeposit(uint256[] calldata) external; function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128); function claimRewards(SwapData[] calldata) external; function emergencyWithdraw(address recipient, uint256[] calldata data) external; function initialize() external; function disable() external; } struct ProcessReallocationData { uint128 sharesToWithdraw; uint128 optimizedShares; uint128 optimizedWithdrawnAmount; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../external/@openzeppelin/utils/SafeCast.sol"; /** * @notice A collection of custom math ustils used throughout the system */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { return SafeCast.toUint128(((mul1 * mul2) / div)); } function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { unchecked { return uint128((mul1 * mul2) / div); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** @notice Handle setting zero value in a storage word as uint128 max value. * * @dev * The purpose of this is to avoid resetting a storage word to the zero value; * the gas cost of re-initializing the value is the same as setting the word originally. * so instead, if word is to be set to zero, we set it to uint128 max. * * - anytime a word is loaded from storage: call "get" * - anytime a word is written to storage: call "set" * - common operations on uints are also bundled here. * * NOTE: This library should ONLY be used when reading or writing *directly* from storage. */ library Max128Bit { uint128 internal constant ZERO = type(uint128).max; function get(uint128 a) internal pure returns(uint128) { return (a == ZERO) ? 0 : a; } function set(uint128 a) internal pure returns(uint128){ return (a == 0) ? ZERO : a; } function add(uint128 a, uint128 b) internal pure returns(uint128 c){ a = get(a); c = set(a + b); } } // SPDX-License-Identifier: BUSL-1.1 import "../interfaces/ISwapData.sol"; pragma solidity 0.8.11; /// @notice Strategy struct for all strategies struct Strategy { uint128 totalShares; /// @notice Denotes strategy completed index uint24 index; /// @notice Denotes whether strategy is removed /// @dev after removing this value can never change, hence strategy cannot be added back again bool isRemoved; /// @notice Pending geposit amount and pending shares withdrawn by all users for next index Pending pendingUser; /// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index Pending pendingUserNext; /// @dev Usually a temp variable when compounding mapping(address => uint256) pendingRewards; /// @dev Usually a temp variable when compounding uint128 pendingDepositReward; /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it uint256 lpTokens; // ----- REALLOCATION VARIABLES ----- bool isInDepositPhase; /// @notice Used to store amount of optimized shares, so they can be substracted at the end /// @dev Only for temporary use, should be reset to 0 in same transaction uint128 optimizedSharesWithdrawn; /// @dev Underlying amount pending to be deposited from other strategies at reallocation /// @dev resets after the strategy reallocation DHW is finished uint128 pendingReallocateDeposit; /// @notice Stores amount of optimized underlying amount when reallocating /// @dev resets after the strategy reallocation DHW is finished /// @dev This is "virtual" amount that was matched between this strategy and others when reallocating uint128 pendingReallocateOptimizedDeposit; // ------------------------------------ /// @notice Total underlying amoung at index mapping(uint256 => TotalUnderlying) totalUnderlying; /// @notice Batches stored after each DHW with index as a key /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users mapping(uint256 => Batch) batches; /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate) /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation mapping(uint256 => BatchReallocation) reallocationBatches; /// @notice Vaults holding this strategy shares mapping(address => Vault) vaults; /// @notice Future proof storage mapping(bytes32 => AdditionalStorage) additionalStorage; /// @dev Make sure to reset it to 0 after emergency withdrawal uint256 emergencyPending; } /// @notice Unprocessed deposit underlying amount and strategy share amount from users struct Pending { uint128 deposit; uint128 sharesToWithdraw; } /// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index struct TotalUnderlying { uint128 amount; uint128 totalShares; } /// @notice Stored after executing DHW for each index. /// @dev This is used for vaults to redeem their deposit. struct Batch { /// @notice total underlying deposited in index uint128 deposited; uint128 depositedReceived; uint128 depositedSharesReceived; uint128 withdrawnShares; uint128 withdrawnReceived; } /// @notice Stored after executing reallocation DHW each index. struct BatchReallocation { /// @notice Deposited amount received from reallocation uint128 depositedReallocation; /// @notice Received shares from reallocation uint128 depositedReallocationSharesReceived; /// @notice Used to know how much tokens was received for reallocating uint128 withdrawnReallocationReceived; /// @notice Amount of shares to withdraw for reallocation uint128 withdrawnReallocationShares; } /// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working) struct Vault { uint128 shares; /// @notice Withdrawn amount as part of the reallocation uint128 withdrawnReallocationShares; /// @notice Index to action mapping(uint256 => VaultBatch) vaultBatches; } /// @notice Stores deposited and withdrawn shares by the vault struct VaultBatch { /// @notice Vault index to deposited amount mapping uint128 deposited; /// @notice Vault index to withdrawn user shares mapping uint128 withdrawnShares; } /// @notice Used for reallocation calldata struct VaultData { address vault; uint8 strategiesCount; uint256 strategiesBitwise; uint256 newProportions; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the withdraw part of the reallocation DHW struct ReallocationWithdrawData { uint256[][] reallocationTable; StratUnderlyingSlippage[] priceSlippages; RewardSlippages[] rewardSlippages; uint256[] stratIndexes; uint256[][] slippages; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the deposit part of the reallocation DHW struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; } /// @notice In case some adapters need extra storage struct AdditionalStorage { uint256 value; address addressValue; uint96 value96; } /// @notice Strategy total underlying slippage, to verify validity of the strategy state struct StratUnderlyingSlippage { uint128 min; uint128 max; } /// @notice Containig information if and how to swap strategy rewards at the DHW /// @dev Passed in by the do-hard-worker struct RewardSlippages { bool doClaim; SwapData[] swapData; } /// @notice Helper struct to compare strategy share between eachother /// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating) struct PriceData { uint128 totalValue; uint128 totalShares; } /// @notice Strategy reallocation values after reallocation optimization of shares was calculated struct ReallocationShares { uint128[] optimizedWithdraws; uint128[] optimizedShares; uint128[] totalSharesWithdrawn; } /// @notice Shared storage for multiple strategies /// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool) struct StrategiesShared { uint184 value; uint32 lastClaimBlock; uint32 lastUpdateBlock; uint8 stratsCount; mapping(uint256 => address) stratAddresses; mapping(bytes32 => uint256) bytesValues; } /// @notice Base storage shared betweek Spool contract and Strategies /// @dev this way we can use same values when performing delegate call /// to strategy implementations from the Spool contract abstract contract BaseStorage { // ----- DHW VARIABLES ----- /// @notice Force while DHW (all strategies) to be executed in only one transaction /// @dev This is enforced to increase the gas efficiency of the system /// Can be removed by the DAO if gas gost of the strategies goes over the block limit bool internal forceOneTxDoHardWork; /// @notice Global index of the system /// @dev Insures the correct strategy DHW execution. /// Every strategy in the system must be equal or one less than global index value /// Global index increments by 1 on every do-hard-work uint24 public globalIndex; /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed uint8 internal doHardWorksLeft; // ----- REALLOCATION VARIABLES ----- /// @notice Used for offchain execution to get the new reallocation table. bool internal logReallocationTable; /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index /// @dev only used when reallocating /// after it reaches 0, deposit phase of the reallocation can begin uint8 public withdrawalDoHardWorksLeft; /// @notice Index at which next reallocation is set uint24 public reallocationIndex; /// @notice 2D table hash containing information of how strategies should be reallocated between eachother /// @dev Created when allocation provider sets reallocation for the vaults /// This table is stored as a hash in the system and verified on reallocation DHW /// Resets to 0 after reallocation DHW is completed bytes32 internal reallocationTableHash; /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating. /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton /// Resets when DHW is completed bytes32 internal reallocationStrategiesHash; // ----------------------------------- /// @notice Denoting if an address is the do-hard-worker mapping(address => bool) public isDoHardWorker; /// @notice Denoting if an address is the allocation provider mapping(address => bool) public isAllocationProvider; /// @notice Strategies shared storage /// @dev used as a helper storage to save common inoramation mapping(bytes32 => StrategiesShared) internal strategiesShared; /// @notice Mapping of strategy implementation address to strategy system values mapping(address => Strategy) public strategies; /// @notice Flag showing if disable was skipped when a strategy has been removed /// @dev If true disable can still be run mapping(address => bool) internal _skippedDisable; /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed /// @dev If true emergency withdraw can still be executed mapping(address => bool) internal _awaitingEmergencyWithdraw; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; /// @title Common Spool contracts constants abstract contract BaseConstants { /// @dev 2 digits precision uint256 internal constant FULL_PERCENT = 100_00; /// @dev Accuracy when doing shares arithmetics uint256 internal constant ACCURACY = 10**30; } /// @title Contains USDC token related values abstract contract USDC { /// @notice USDC token contract address IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/GNSPS-solidity-bytes-utils/BytesLib.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../external/uniswap/interfaces/ISwapRouter02.sol"; import "../interfaces/ISwapData.sol"; /// @notice Denotes swap action mode enum SwapAction { NONE, UNI_V2_DIRECT, UNI_V2_WETH, UNI_V2, UNI_V3_DIRECT, UNI_V3_WETH, UNI_V3 } /// @title Contains logic facilitating swapping using Uniswap abstract contract SwapHelper { using BytesLib for bytes; using SafeERC20 for IERC20; /// @dev The length of the bytes encoded swap action uint256 private constant ACTION_SIZE = 1; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev Maximum V2 path length (4 swaps) uint256 private constant MAX_V2_PATH = ADDR_SIZE * 3; /// @dev V3 WETH path length uint256 private constant WETH_V3_PATH_SIZE = FEE_SIZE + FEE_SIZE; /// @dev Minimum V3 custom path length (2 swaps) uint256 private constant MIN_V3_PATH = FEE_SIZE + NEXT_OFFSET; /// @dev Maximum V3 path length (4 swaps) uint256 private constant MAX_V3_PATH = FEE_SIZE + NEXT_OFFSET * 3; /// @notice Uniswap router supporting Uniswap V2 and V3 ISwapRouter02 internal immutable uniswapRouter; /// @notice Address of WETH token address private immutable WETH; /** * @notice Sets initial values * @param _uniswapRouter Uniswap router address * @param _WETH WETH token address */ constructor(ISwapRouter02 _uniswapRouter, address _WETH) { uniswapRouter = _uniswapRouter; WETH = _WETH; } /** * @notice Approve reward token and swap the `amount` to a strategy underlying asset * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param swapData Swap details showing the path of the swap * @return result Amount of underlying (`to`) tokens recieved */ function _approveAndSwap( IERC20 from, IERC20 to, uint256 amount, SwapData calldata swapData ) internal virtual returns (uint256) { // if there is nothing to swap, return if(amount == 0) return 0; // if amount is not uint256 max approve unswap router to spend tokens // otherwise rewards were already sent to the router if(amount < type(uint256).max) { from.safeApprove(address(uniswapRouter), amount); } else { amount = 0; } // get swap action from first byte SwapAction action = SwapAction(swapData.path.toUint8(0)); uint256 result; if (action == SwapAction.UNI_V2_DIRECT) { // V2 Direct address[] memory path = new address[](2); result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V2_WETH) { // V2 WETH address[] memory path = new address[](3); path[1] = WETH; result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V2) { // V2 Custom address[] memory path = _getV2Path(swapData.path); result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V3_DIRECT) { // V3 Direct result = _swapDirectV3(from, to, amount, swapData.slippage, swapData.path); } else if (action == SwapAction.UNI_V3_WETH) { // V3 WETH bytes memory wethPath = _getV3WethPath(swapData.path); result = _swapV3(from, to, amount, swapData.slippage, wethPath); } else if (action == SwapAction.UNI_V3) { // V3 Custom require(swapData.path.length > MIN_V3_PATH, "SwapHelper::_approveAndSwap: Path too short"); uint256 actualpathSize = swapData.path.length - ACTION_SIZE; require((actualpathSize - FEE_SIZE) % NEXT_OFFSET == 0 && actualpathSize <= MAX_V3_PATH, "SwapHelper::_approveAndSwap: Bad V3 path"); result = _swapV3(from, to, amount, swapData.slippage, swapData.path[ACTION_SIZE:]); } else { revert("SwapHelper::_approveAndSwap: No action"); } if (from.allowance(address(this), address(uniswapRouter)) > 0) { from.safeApprove(address(uniswapRouter), 0); } return result; } /** * @notice Swaps tokens using Uniswap V2 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param path Steps to complete the swap * @return result Amount of underlying (`to`) tokens recieved */ function _swapV2( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, address[] memory path ) internal virtual returns (uint256) { path[0] = address(from); path[path.length - 1] = address(to); return uniswapRouter.swapExactTokensForTokens( amount, slippage, path, address(this) ); } /** * @notice Swaps tokens using Uniswap V3 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param path Steps to complete the swap * @return result Amount of underlying (`to`) tokens recieved */ function _swapV3( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, bytes memory path ) internal virtual returns (uint256) { IV3SwapRouter.ExactInputParams memory params = IV3SwapRouter.ExactInputParams({ path: abi.encodePacked(address(from), path, address(to)), recipient: address(this), amountIn: amount, amountOutMinimum: slippage }); // Executes the swap. uint received = uniswapRouter.exactInput(params); return received; } /** * @notice Does a direct swap from `from` address to the `to` address using Uniswap V3 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param fee V3 direct fee configuration * @return result Amount of underlying (`to`) tokens recieved */ function _swapDirectV3( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, bytes memory fee ) internal virtual returns (uint256) { require(fee.length == FEE_SIZE + ACTION_SIZE, "SwapHelper::_swapDirectV3: Bad V3 direct fee"); IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams( address(from), address(to), // ignore first byte fee.toUint24(ACTION_SIZE), address(this), amount, slippage, 0 ); return uniswapRouter.exactInputSingle(params); } /** * @notice Converts passed bytes to V2 path * @param pathBytes Swap path in bytes, converted to addresses * @return path list of addresses in the swap path (skipping first and last element) */ function _getV2Path(bytes calldata pathBytes) internal pure returns(address[] memory) { require(pathBytes.length > ACTION_SIZE, "SwapHelper::_getV2Path: No path provided"); uint256 actualpathSize = pathBytes.length - ACTION_SIZE; require(actualpathSize % ADDR_SIZE == 0 && actualpathSize <= MAX_V2_PATH, "SwapHelper::_getV2Path: Bad V2 path"); uint256 pathLength = actualpathSize / ADDR_SIZE; address[] memory path = new address[](pathLength + 2); // ignore first byte path[1] = pathBytes.toAddress(ACTION_SIZE); for (uint256 i = 1; i < pathLength; i++) { path[i + 1] = pathBytes.toAddress(i * ADDR_SIZE + ACTION_SIZE); } return path; } /** * @notice Get Unswap V3 path to swap tokens via WETH LP pool * @param pathBytes Swap path in bytes * @return wethPath Unswap V3 path routing via WETH pool */ function _getV3WethPath(bytes calldata pathBytes) internal view returns(bytes memory) { require(pathBytes.length == WETH_V3_PATH_SIZE + ACTION_SIZE, "SwapHelper::_getV3WethPath: Bad V3 WETH path"); // ignore first byte as it's used for swap action return abi.encodePacked(pathBytes[ACTION_SIZE:4], WETH, pathBytes[4:]); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./SwapHelper.sol"; /// @title Swap helper implementation with SwapRouter02 on Mainnet contract SwapHelperMainnet is SwapHelper { constructor() SwapHelper(ISwapRouter02(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {} } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../interfaces/IBaseStrategy.sol"; import "../shared/BaseStorage.sol"; import "../shared/Constants.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../libraries/Math.sol"; import "../libraries/Max/128Bit.sol"; /** * @notice Implementation of the {IBaseStrategy} interface. * * @dev * This implementation of the {IBaseStrategy} is meant to operate * on single-collateral strategies and uses a delta system to calculate * whether a withdrawal or deposit needs to be performed for a particular * strategy. */ abstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants { using SafeERC20 for IERC20; using Max128Bit for uint128; /* ========== CONSTANTS ========== */ /// @notice minimum shares size to avoid loss of share due to computation precision uint128 private constant MIN_SHARES = 10**8; /* ========== STATE VARIABLES ========== */ /// @notice The total slippage slots the strategy supports, used for validation of provided slippage uint256 internal immutable rewardSlippageSlots; /// @notice Slots for processing uint256 internal immutable processSlippageSlots; /// @notice Slots for reallocation uint256 internal immutable reallocationSlippageSlots; /// @notice Slots for deposit uint256 internal immutable depositSlippageSlots; /** * @notice do force claim of rewards. * * @dev * Some strategies auto claim on deposit/withdraw, * so execute the claim actions to store the reward amounts. */ bool internal immutable forceClaim; /// @notice flag to force balance validation before running process strategy /// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system bool internal immutable doValidateBalance; /// @notice The self address, set at initialization to allow proper share accounting address internal immutable self; /// @notice The underlying asset of the strategy IERC20 public immutable override underlying; /* ========== CONSTRUCTOR ========== */ /** * @notice Initializes the base strategy values. * * @dev * It performs certain pre-conditional validations to ensure the contract * has been initialized properly, such as that the address argument of the * underlying asset is valid. * * Slippage slots for certain strategies may be zero if there is no compounding * work to be done. * * @param _underlying token used for deposits * @param _rewardSlippageSlots slots for rewards * @param _processSlippageSlots slots for processing * @param _reallocationSlippageSlots slots for reallocation * @param _depositSlippageSlots slots for deposits * @param _forceClaim force claim of rewards * @param _doValidateBalance force balance validation */ constructor( IERC20 _underlying, uint256 _rewardSlippageSlots, uint256 _processSlippageSlots, uint256 _reallocationSlippageSlots, uint256 _depositSlippageSlots, bool _forceClaim, bool _doValidateBalance ) { require( _underlying != IERC20(address(0)), "BaseStrategy::constructor: Underlying address cannot be 0" ); self = address(this); underlying = _underlying; rewardSlippageSlots = _rewardSlippageSlots; processSlippageSlots = _processSlippageSlots; reallocationSlippageSlots = _reallocationSlippageSlots; depositSlippageSlots = _depositSlippageSlots; forceClaim = _forceClaim; doValidateBalance = _doValidateBalance; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Process the latest pending action of the strategy * * @dev * it yields amount of funds processed as well as the reward buffer of the strategy. * The function will auto-compound rewards if requested and supported. * * Requirements: * * - the slippages provided must be valid in length * - if the redeposit flag is set to true, the strategy must support * compounding of rewards * * @param slippages slippages to process * @param redeposit if redepositing is to occur * @param swapData swap data for processing */ function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override { slippages = _validateStrategyBalance(slippages); if (forceClaim || redeposit) { _validateRewardsSlippage(swapData); _processRewards(swapData); } if (processSlippageSlots != 0) _validateProcessSlippage(slippages); _process(slippages, 0); } /** * @notice Process first part of the reallocation DHW * @dev Withdraws for reallocation, depositn and withdraww for a user * * @param slippages Parameters to apply when performing a deposit or a withdraw * @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw * @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw */ function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); if (reallocationSlippageSlots != 0) _validateReallocationSlippage(slippages); _process(slippages, processReallocationData.sharesToWithdraw); uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData); return withdrawnReallocationReceived; } /** * @dev Update reallocation batch storage for index after withdrawing reallocated shares * @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw * @return Withdrawn reallocation received */ function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint24 stratIndex = _getProcessingIndex(); BatchReallocation storage batch = strategy.reallocationBatches[stratIndex]; // save actual withdrawn amount, without optimized one uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived; strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares; batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount; batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw; return withdrawnReallocationReceived; } /** * @notice Process deposit * @param slippages Array of slippage parameters to apply when depositing */ function processDeposit(uint256[] calldata slippages) external override { slippages = _validateStrategyBalance(slippages); if (depositSlippageSlots != 0) _validateDepositSlippage(slippages); _processDeposit(slippages); } /** * @notice Returns total starategy balance includign pending rewards * @return strategyBalance total starategy balance includign pending rewards */ function getStrategyUnderlyingWithRewards() public view override returns(uint128) { return _getStrategyUnderlyingWithRewards(); } /** * @notice Fast withdraw * @param shares Shares to fast withdraw * @param slippages Array of slippage parameters to apply when withdrawing * @param swapData Swap slippage and path array * @return Withdrawn amount withdawn */ function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); _validateRewardsSlippage(swapData); if (processSlippageSlots != 0) _validateProcessSlippage(slippages); uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData); strategies[self].totalShares -= shares; return withdrawnAmount; } /** * @notice Claims and possibly compounds strategy rewards. * * @param swapData swap data for processing */ function claimRewards(SwapData[] calldata swapData) external override { _validateRewardsSlippage(swapData); _processRewards(swapData); } /** * @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process. * * @param recipient recipient of the withdrawn funds * @param data data necessary execute the emergency withdraw */ function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override { uint256 balanceBefore = underlying.balanceOf(address(this)); _emergencyWithdraw(recipient, data); uint256 balanceAfter = underlying.balanceOf(address(this)); uint256 withdrawnAmount = 0; if (balanceAfter > balanceBefore) { withdrawnAmount = balanceAfter - balanceBefore; } Strategy storage strategy = strategies[self]; if (strategy.emergencyPending > 0) { withdrawnAmount += strategy.emergencyPending; strategy.emergencyPending = 0; } // also withdraw all unprocessed deposit for a strategy if (strategy.pendingUser.deposit.get() > 0) { withdrawnAmount += strategy.pendingUser.deposit.get(); strategy.pendingUser.deposit = 0; } if (strategy.pendingUserNext.deposit.get() > 0) { withdrawnAmount += strategy.pendingUserNext.deposit.get(); strategy.pendingUserNext.deposit = 0; } // if strategy was already processed in the current index that hasn't finished yet, // transfer the withdrawn amount // reset total underlying to 0 if (strategy.index == globalIndex && doHardWorksLeft > 0) { uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived; withdrawnAmount += withdrawnReceived; strategy.batches[strategy.index].withdrawnReceived = 0; strategy.totalUnderlying[strategy.index].amount = 0; } if (withdrawnAmount > 0) { // check if the balance is high enough to withdraw the total withdrawnAmount if (balanceAfter < withdrawnAmount) { // if not withdraw the current balance withdrawnAmount = balanceAfter; } underlying.safeTransfer(recipient, withdrawnAmount); } } /** * @notice Initialize a strategy. * @dev Execute strategy specific one-time actions if needed. */ function initialize() external virtual override {} /** * @notice Disables a strategy. * @dev Cleans strategy specific values if needed. */ function disable() external virtual override {} /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Validate strategy balance * @param slippages Check if the strategy balance is within defined min and max values * @return slippages Same array without first 2 slippages */ function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) { if (doValidateBalance) { require(slippages.length >= 2, "BaseStrategy:: _validateStrategyBalance: Invalid number of slippages"); uint128 strategyBalance = getStrategyBalance(); require( slippages[0] <= strategyBalance && slippages[1] >= strategyBalance, "BaseStrategy::_validateStrategyBalance: Bad strategy balance" ); return slippages[2:]; } return slippages; } /** * @dev Validate reards slippage * @param swapData Swap slippage and path array */ function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual { if (swapData.length > 0) { require( swapData.length == _getRewardSlippageSlots(), "BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined" ); } } /** * @dev Retrieve reward slippage slots * @return Reward slippage slots */ function _getRewardSlippageSlots() internal view virtual returns(uint256) { return rewardSlippageSlots; } /** * @dev Validate process slippage * @param slippages parameters to verify validity of the strategy state */ function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, processSlippageSlots); } /** * @dev Validate reallocation slippage * @param slippages parameters to verify validity of the strategy state */ function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, reallocationSlippageSlots); } /** * @dev Validate deposit slippage * @param slippages parameters to verify validity of the strategy state */ function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, depositSlippageSlots); } /** * @dev Validates the provided slippage in length. * @param currentLength actual slippage array length * @param shouldBeLength expected slippages array length */ function _validateSlippage(uint256 currentLength, uint256 shouldBeLength) internal view virtual { require( currentLength == shouldBeLength, "BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined" ); } /** * @dev Retrieve processing index * @return Processing index */ function _getProcessingIndex() internal view returns(uint24) { return strategies[self].index + 1; } /** * @dev Calculates shares before they are added to the total shares * @param strategyTotalShares Total shares for strategy * @param stratTotalUnderlying Total underlying for strategy * @return newShares New shares calculated */ function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ uint128 oldUnderlying; if (stratTotalUnderlying > depositAmount) { oldUnderlying = stratTotalUnderlying - depositAmount; } if (strategyTotalShares == 0 || oldUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, oldUnderlying); } } /** * @dev Calculates shares when they are already part of the total shares * * @param strategyTotalShares Total shares * @param stratTotalUnderlying Total underlying * @return newShares New shares calculated */ function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ if (strategyTotalShares == 0 || stratTotalUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying); } } /** * @dev Reset allowance to zero if previously set to a higher value. * @param token Asset * @param spender Spender address */ function _resetAllowance(IERC20 token, address spender) internal { if (token.allowance(address(this), spender) > 0) { token.safeApprove(spender, 0); } } /* ========== VIRTUAL FUNCTIONS ========== */ function getStrategyBalance() public view virtual override returns (uint128); function _processRewards(SwapData[] calldata) internal virtual; function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual; function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual; function _processDeposit(uint256[] memory) internal virtual; function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128); function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./RewardStrategy.sol"; import "../shared/SwapHelperMainnet.sol"; /** * @notice Claim full single reward strategy logic */ abstract contract ClaimFullSingleRewardStrategy is RewardStrategy, SwapHelperMainnet { /* ========== STATE VARIABLES ========== */ IERC20 internal immutable rewardToken; /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _rewardToken Reward token contract */ constructor( IERC20 _rewardToken ) { require(address(_rewardToken) != address(0), "ClaimFullSingleRewardStrategy::constructor: Token address cannot be 0"); rewardToken = _rewardToken; } /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Claim rewards * @param swapData Slippage and path array * @return Rewards */ function _claimRewards(SwapData[] calldata swapData) internal override returns(Reward[] memory) { return _claimSingleRewards(type(uint128).max, swapData); } /** * @dev Claim fast withdraw rewards * @param shares Amount of shares * @param swapData Swap slippage and path * @return Rewards */ function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal override returns(Reward[] memory) { return _claimSingleRewards(shares, swapData); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @dev Claim single rewards * @param shares Amount of shares * @param swapData Swap slippage and path * @return rewards Collected reward amounts */ function _claimSingleRewards(uint128 shares, SwapData[] calldata swapData) private returns(Reward[] memory rewards) { if (swapData.length > 0 && swapData[0].slippage > 0) { uint128 rewardAmount = _claimStrategyReward(); if (rewardAmount > 0) { Strategy storage strategy = strategies[self]; uint128 claimedAmount = _getRewardClaimAmount(shares, rewardAmount); rewards = new Reward[](1); rewards[0] = Reward(claimedAmount, rewardToken); // if we don't claim all the rewards save the amount left, otherwise reset amount left to 0 if (rewardAmount > claimedAmount) { uint128 rewardAmountLeft = rewardAmount - claimedAmount; strategy.pendingRewards[address(rewardToken)] = rewardAmountLeft; } else if (strategy.pendingRewards[address(rewardToken)] > 0) { strategy.pendingRewards[address(rewardToken)] = 0; } } } } /* ========== VIRTUAL FUNCTIONS ========== */ function _claimStrategyReward() internal virtual returns(uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./BaseStrategy.sol"; import "../libraries/Max/128Bit.sol"; import "../libraries/Math.sol"; struct ProcessInfo { uint128 totalWithdrawReceived; uint128 userDepositReceived; } /** * @notice Process strategy logic */ abstract contract ProcessStrategy is BaseStrategy { using Max128Bit for uint128; /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards * @dev * Deposit amount amd withdrawal shares are matched between eachother, effecively only one of * those 2 is called. Shares are converted to the dollar value, based on the current strategy * total balance. This ensures the minimum amount of assets are moved around to lower the price * drift and total fees paid to the protocols the strategy is interacting with (if there are any) * * @param slippages Strategy slippage values verifying the validity of the strategy state * @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0) */ function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual { // PREPARE Strategy storage strategy = strategies[self]; uint24 processingIndex = _getProcessingIndex(); Batch storage batch = strategy.batches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get(); uint128 userDeposit = strategy.pendingUser.deposit.get(); // CALCULATE THE ACTION // if withdrawing for reallocating, add shares to total withdraw shares if (reallocateSharesToWithdraw > 0) { pendingSharesToWithdraw += reallocateSharesToWithdraw; } // total deposit received from users + compound reward (if there are any) uint128 totalPendingDeposit = userDeposit; // add compound reward (pendingDepositReward) to deposit uint128 withdrawalReward = 0; if (strategy.pendingDepositReward > 0) { uint128 pendingDepositReward = strategy.pendingDepositReward; totalPendingDeposit += pendingDepositReward; // calculate compound reward (withdrawalReward) for users withdrawing in this batch if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) { withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares); // substract withdrawal reward from total deposit totalPendingDeposit -= withdrawalReward; } // Reset pendingDepositReward strategy.pendingDepositReward = 0; } // if there is no pending deposit or withdrawals, return if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) { return; } uint128 pendingWithdrawalAmount = 0; if (pendingSharesToWithdraw > 0) { pendingWithdrawalAmount = Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares); } // ACTION: DEPOSIT OR WITHDRAW ProcessInfo memory processInfo; if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT // uint128 amount = totalPendingDeposit - pendingWithdrawalAmount; uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages); processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; // pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount; uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount; // calculate user deposit received, excluding compound rewards processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit); } else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW // uint128 amount = pendingWithdrawalAmount - totalPendingDeposit; uint128 withdrawReceived = _withdraw( // calculate back the shares from actual withdraw amount // NOTE: we can do unchecked calculation and casting as // the multiplier is always smaller than the divisor Math.getProportion128Unchecked( (pendingWithdrawalAmount - totalPendingDeposit), pendingSharesToWithdraw, pendingWithdrawalAmount ), slippages ); // optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit; processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward; processInfo.userDepositReceived = userDeposit; } else { processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; processInfo.userDepositReceived = userDeposit; } // UPDATE STORAGE AFTER { uint128 stratTotalUnderlying = getStrategyBalance(); // Update withdraw batch if (pendingSharesToWithdraw > 0) { batch.withdrawnReceived = processInfo.totalWithdrawReceived; batch.withdrawnShares = pendingSharesToWithdraw; strategyTotalShares -= pendingSharesToWithdraw; // update reallocation batch if (reallocateSharesToWithdraw > 0) { BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 withdrawnReallocationReceived = Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw); reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived; // substract reallocation values from user values batch.withdrawnReceived -= withdrawnReallocationReceived; batch.withdrawnShares -= reallocateSharesToWithdraw; } } // Update deposit batch if (userDeposit > 0) { uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived); batch.deposited = userDeposit; batch.depositedReceived = processInfo.userDepositReceived; batch.depositedSharesReceived = newShares; strategyTotalShares += newShares; } // Update shares if (strategyTotalShares != strategy.totalShares) { strategy.totalShares = strategyTotalShares; } // Set underlying at index strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; } } /** * @notice Process deposit * @param slippages Slippages array */ function _processDeposit(uint256[] memory slippages) internal override virtual { Strategy storage strategy = strategies[self]; uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit; uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn; uint128 depositAmount = strategy.pendingReallocateDeposit; // if a strategy is not part of reallocation return if ( depositOptimizedAmount == 0 && optimizedSharesWithdrawn == 0 && depositAmount == 0 ) { return; } uint24 processingIndex = _getProcessingIndex(); BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; // get shares from optimized deposit if (depositOptimizedAmount > 0) { uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation = depositOptimizedAmount; reallocationBatch.depositedReallocationSharesReceived = newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateOptimizedDeposit = 0; } // remove optimized withdraw shares if (optimizedSharesWithdrawn > 0) { strategyTotalShares -= optimizedSharesWithdrawn; // reset strategy.optimizedSharesWithdrawn = 0; } // get shares from actual deposit if (depositAmount > 0) { // deposit uint128 depositReceived = _deposit(depositAmount, slippages); // NOTE: might return it from _deposit (only certain strategies need it) uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation += depositReceived; reallocationBatch.depositedReallocationSharesReceived += newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateDeposit = 0; } // update share storage strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; strategy.totalShares = strategyTotalShares; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice get the value of the strategy shares in the underlying tokens * @param shares Number of shares * @return amount Underling amount representing the `share` value of the strategy */ function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) { amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares ); } /** * @notice get slippage amount, and action type (withdraw/deposit). * @dev * Most significant bit represents an action, 0 for a withdrawal and 1 for deposit. * * This ensures the slippage will be used for the action intended by the do-hard-worker, * otherwise the transavtion will revert. * * @param slippageAction number containing the slippage action and the actual slippage amount * @return isDeposit Flag showing if the slippage is for the deposit action * @return slippage the slippage value cleaned of the most significant bit */ function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) { // remove most significant bit slippage = (slippageAction << 1) >> 1; // if values are not the same (the removed bit was 1) set action to deposit if (slippageAction != slippage) { isDeposit = true; } } /* ========== VIRTUAL FUNCTIONS ========== */ function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived); function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./ProcessStrategy.sol"; import "../shared/SwapHelper.sol"; struct Reward { uint256 amount; IERC20 token; } /** * @notice Reward strategy logic */ abstract contract RewardStrategy is ProcessStrategy, SwapHelper { /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Gey strategy underlying asset with rewards * @return Total underlying */ function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint128 totalUnderlying = getStrategyBalance(); totalUnderlying += strategy.pendingDepositReward; return totalUnderlying; } /** * @notice Process an instant withdrawal from the protocol per users request. * * @param shares Amount of shares * @param slippages Array of slippages * @param swapData Data used in processing * @return Withdrawn amount */ function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata swapData) internal override virtual returns(uint128) { uint128 withdrawRewards = _processFastWithdrawalRewards(shares, swapData); uint128 withdrawReceived = _withdraw(shares, slippages); return withdrawReceived + withdrawRewards; } /** * @notice Process rewards * @param swapData Data used in processing */ function _processRewards(SwapData[] calldata swapData) internal override virtual { Strategy storage strategy = strategies[self]; Reward[] memory rewards = _claimRewards(swapData); uint128 collectedAmount = _sellRewards(rewards, swapData); if (collectedAmount > 0) { strategy.pendingDepositReward += collectedAmount; } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Process fast withdrawal rewards * @param shares Amount of shares * @param swapData Values used for swapping the rewards * @return withdrawalRewards Withdrawal rewards */ function _processFastWithdrawalRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(uint128 withdrawalRewards) { Strategy storage strategy = strategies[self]; Reward[] memory rewards = _claimFastWithdrawRewards(shares, swapData); withdrawalRewards += _sellRewards(rewards, swapData); if (strategy.pendingDepositReward > 0) { uint128 fastWithdrawCompound = Math.getProportion128(strategy.pendingDepositReward, shares, strategy.totalShares); if (fastWithdrawCompound > 0) { strategy.pendingDepositReward -= fastWithdrawCompound; withdrawalRewards += fastWithdrawCompound; } } } /** * @notice Sell rewards to the underlying token * @param rewards Rewards to sell * @param swapData Values used for swapping the rewards * @return collectedAmount Collected underlying amount */ function _sellRewards(Reward[] memory rewards, SwapData[] calldata swapData) internal virtual returns(uint128 collectedAmount) { for (uint256 i = 0; i < rewards.length; i++) { // add compound amount from current batch to the fast withdraw if (rewards[i].amount > 0) { uint128 compoundAmount = SafeCast.toUint128( _approveAndSwap( rewards[i].token, underlying, rewards[i].amount, swapData[i] ) ); // add to pending reward collectedAmount += compoundAmount; } } } /** * @notice Get reward claim amount for `shares` * @param shares Amount of shares * @param rewardAmount Total reward amount * @return rewardAmount Amount of reward for the shares */ function _getRewardClaimAmount(uint128 shares, uint256 rewardAmount) internal virtual view returns(uint128) { // for do hard work claim everything if (shares == type(uint128).max) { return SafeCast.toUint128(rewardAmount); } else { // for fast withdrawal claim calculate user withdraw amount return SafeCast.toUint128((rewardAmount * shares) / strategies[self].totalShares); } } /* ========== VIRTUAL FUNCTIONS ========== */ function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../ClaimFullSingleRewardStrategy.sol"; import "../../external/interfaces/harvest/Vault/IHarvestVault.sol"; import "../../external/interfaces/harvest/IHarvestPool.sol"; /** * @notice Harvest strategy implementation */ contract HarvestStrategy is ClaimFullSingleRewardStrategy { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ /// @notice Harvest vault contract IHarvestVault public immutable vault; /// @notice Harvest pool contract IHarvestPool public immutable pool; /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _farm Farm contract * @param _vault Vault contract * @param _pool Pool contract * @param _underlying Underlying asset */ constructor( IERC20 _farm, IHarvestVault _vault, IHarvestPool _pool, IERC20 _underlying ) BaseStrategy(_underlying, 1, 0, 0, 0, false, false) ClaimFullSingleRewardStrategy(_farm) { require(address(_vault) != address(0), "HarvestStrategy::constructor: Vault address cannot be 0"); require(address(_pool) != address(0), "HarvestStrategy::constructor: Pool address cannot be 0"); vault = _vault; pool = _pool; } /* ========== VIEWS ========== */ /** * @notice Get strategy balance * @return Strategy balance */ function getStrategyBalance() public view override returns(uint128) { uint256 fTokenBalance = pool.balanceOf(address(this)); return SafeCast.toUint128(_getfTokenValue(fTokenBalance)); } /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @dev Claim strategy reward * @return Reward amount */ function _claimStrategyReward() internal override returns(uint128) { // claim uint256 rewardBefore = rewardToken.balanceOf(address(this)); pool.getReward(); uint256 rewardAmount = rewardToken.balanceOf(address(this)) - rewardBefore; // add already claimed rewards rewardAmount += strategies[self].pendingRewards[address(rewardToken)]; return SafeCast.toUint128(rewardAmount); } /** * @dev Deposit * @param amount Amount to deposit * @return Deposited amount */ function _deposit(uint128 amount, uint256[] memory) internal override returns(uint128) { // deposit underlying underlying.safeApprove(address(vault), amount); uint256 fTokenBefore = vault.balanceOf(address(this)); vault.deposit(amount); uint256 fTokenNew = vault.balanceOf(address(this)) - fTokenBefore; _resetAllowance(underlying, address(vault)); // stake fTokens vault.approve(address(pool), fTokenNew); pool.stake(fTokenNew); return SafeCast.toUint128(_getfTokenValue(fTokenNew)); } /** * @dev Withdraw * @param shares Shares to withdraw * @return Withdrawn amount */ function _withdraw(uint128 shares, uint256[] memory) internal override returns(uint128) { uint256 fTokensTotal = pool.balanceOf(address(this)); uint256 fWithdrawAmount = (fTokensTotal * shares) / strategies[self].totalShares; // withdraw staked fTokens from pool pool.withdraw(fWithdrawAmount); // withdraw fTokens from vault uint256 undelyingBefore = underlying.balanceOf(address(this)); vault.withdraw(fWithdrawAmount); uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore; return SafeCast.toUint128(undelyingWithdrawn); } /** * @dev Emergency withdraw */ function _emergencyWithdraw(address, uint256[] calldata) internal override { pool.exit(); vault.withdraw(vault.balanceOf(address(this))); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @dev Return value of fTokens in the underlying asset * @param fTokenAmount Amount of fTokens * @return value in the underlying asset */ function _getfTokenValue(uint256 fTokenAmount) private view returns(uint256) { if (fTokenAmount == 0) return 0; uint256 vaultTotal = vault.underlyingBalanceWithInvestment(); return (vaultTotal * fTokenAmount) / vault.totalSupply(); } }
========== STATE VARIABLES ========== / Harvest vault contract Harvest pool contract ========== CONSTRUCTOR ========== / Set initial values _farm Farm contract _vault Vault contract _pool Pool contract _underlying Underlying asset/
function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); } pragma solidity 0.8.11; import "../ClaimFullSingleRewardStrategy.sol"; import "../../external/interfaces/harvest/Vault/IHarvestVault.sol"; import "../../external/interfaces/harvest/IHarvestPool.sol"; { require(address(_vault) != address(0), "HarvestStrategy::constructor: Vault address cannot be 0"); require(address(_pool) != address(0), "HarvestStrategy::constructor: Pool address cannot be 0"); vault = _vault; pool = _pool; }
18,220
./full_match/5/0xF126A8227E92CAEE3455bF9889CB4Acb7FEDB675/sources/contracts/contracts-v10/contracts/UpdateMaster.sol
Conditions for going to Closed ✅
function toClosedConditions(uint256 _projectID) public view returns (bool) { ProjectManager.Project memory project = IStandardSubstrate( standardSubstrateAddress ).getProject(_projectID); bool currentStatusValid = project.status == ProjectManager.ProjectStatus.PostDisp; bool childProjectsClosed = true; for (uint256 i = 0; i < project.childProjects.length; i++) { if ( IStandardSubstrate(standardSubstrateAddress) .getProject(project.childProjects[i]) .status != ProjectManager.ProjectStatus.Closed ) { childProjectsClosed = false; break; } } return currentStatusValid && childProjectsClosed; }
11,602,181
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library JsonWriter { using JsonWriter for string; struct Json { int256 depthBitTracker; string value; } bytes1 constant BACKSLASH = bytes1(uint8(92)); bytes1 constant BACKSPACE = bytes1(uint8(8)); bytes1 constant CARRIAGE_RETURN = bytes1(uint8(13)); bytes1 constant DOUBLE_QUOTE = bytes1(uint8(34)); bytes1 constant FORM_FEED = bytes1(uint8(12)); bytes1 constant FRONTSLASH = bytes1(uint8(47)); bytes1 constant HORIZONTAL_TAB = bytes1(uint8(9)); bytes1 constant NEWLINE = bytes1(uint8(10)); string constant TRUE = "true"; string constant FALSE = "false"; bytes1 constant OPEN_BRACE = "{"; bytes1 constant CLOSED_BRACE = "}"; bytes1 constant OPEN_BRACKET = "["; bytes1 constant CLOSED_BRACKET = "]"; bytes1 constant LIST_SEPARATOR = ","; int256 constant MAX_INT256 = type(int256).max; /** * @dev Writes the beginning of a JSON array. */ function writeStartArray(Json memory json) internal pure returns (Json memory) { return writeStart(json, OPEN_BRACKET); } /** * @dev Writes the beginning of a JSON array with a property name as the key. */ function writeStartArray(Json memory json, string memory propertyName) internal pure returns (Json memory) { return writeStart(json, propertyName, OPEN_BRACKET); } /** * @dev Writes the beginning of a JSON object. */ function writeStartObject(Json memory json) internal pure returns (Json memory) { return writeStart(json, OPEN_BRACE); } /** * @dev Writes the beginning of a JSON object with a property name as the key. */ function writeStartObject(Json memory json, string memory propertyName) internal pure returns (Json memory) { return writeStart(json, propertyName, OPEN_BRACE); } /** * @dev Writes the end of a JSON array. */ function writeEndArray(Json memory json) internal pure returns (Json memory) { return writeEnd(json, CLOSED_BRACKET); } /** * @dev Writes the end of a JSON object. */ function writeEndObject(Json memory json) internal pure returns (Json memory) { return writeEnd(json, CLOSED_BRACE); } /** * @dev Writes the property name and address value (as a JSON string) as part of a name/value pair of a JSON object. */ function writeAddressProperty( Json memory json, string memory propertyName, address value ) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": "', addressToString(value), '"')); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": "', addressToString(value), '"')); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the address value (as a JSON string) as an element of a JSON array. */ function writeAddressValue(Json memory json, address value) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', addressToString(value), '"')); } else { json.value = string(abi.encodePacked(json.value, '"', addressToString(value), '"')); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the property name and boolean value (as a JSON literal "true" or "false") as part of a name/value pair of a JSON object. */ function writeBooleanProperty( Json memory json, string memory propertyName, bool value ) internal pure returns (Json memory) { string memory strValue; if (value) { strValue = TRUE; } else { strValue = FALSE; } if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": ', strValue)); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": ', strValue)); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the boolean value (as a JSON literal "true" or "false") as an element of a JSON array. */ function writeBooleanValue(Json memory json, bool value) internal pure returns (Json memory) { string memory strValue; if (value) { strValue = TRUE; } else { strValue = FALSE; } if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, strValue)); } else { json.value = string(abi.encodePacked(json.value, strValue)); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the property name and int value (as a JSON number) as part of a name/value pair of a JSON object. */ function writeIntProperty( Json memory json, string memory propertyName, int256 value ) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": ', intToString(value))); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": ', intToString(value))); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the int value (as a JSON number) as an element of a JSON array. */ function writeIntValue(Json memory json, int256 value) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, intToString(value))); } else { json.value = string(abi.encodePacked(json.value, intToString(value))); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the property name and value of null as part of a name/value pair of a JSON object. */ function writeNullProperty(Json memory json, string memory propertyName) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": null')); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": null')); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the value of null as an element of a JSON array. */ function writeNullValue(Json memory json) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, "null")); } else { json.value = string(abi.encodePacked(json.value, "null")); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the string text value (as a JSON string) as an element of a JSON array. */ function writeStringProperty( Json memory json, string memory propertyName, string memory value ) internal pure returns (Json memory) { string memory jsonEscapedString = escapeJsonString(value); if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": "', jsonEscapedString, '"')); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": "', jsonEscapedString, '"')); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the property name and string text value (as a JSON string) as part of a name/value pair of a JSON object. */ function writeStringValue(Json memory json, string memory value) internal pure returns (Json memory) { string memory jsonEscapedString = escapeJsonString(value); if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', jsonEscapedString, '"')); } else { json.value = string(abi.encodePacked(json.value, '"', jsonEscapedString, '"')); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the property name and uint value (as a JSON number) as part of a name/value pair of a JSON object. */ function writeUintProperty( Json memory json, string memory propertyName, uint256 value ) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": ', uintToString(value))); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": ', uintToString(value))); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the uint value (as a JSON number) as an element of a JSON array. */ function writeUintValue(Json memory json, uint256 value) internal pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, uintToString(value))); } else { json.value = string(abi.encodePacked(json.value, uintToString(value))); } json.depthBitTracker = setListSeparatorFlag(json); return json; } /** * @dev Writes the beginning of a JSON array or object based on the token parameter. */ function writeStart(Json memory json, bytes1 token) private pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, token)); } else { json.value = string(abi.encodePacked(json.value, token)); } json.depthBitTracker &= MAX_INT256; json.depthBitTracker++; return json; } /** * @dev Writes the beginning of a JSON array or object based on the token parameter with a property name as the key. */ function writeStart( Json memory json, string memory propertyName, bytes1 token ) private pure returns (Json memory) { if (json.depthBitTracker < 0) { json.value = string(abi.encodePacked(json.value, LIST_SEPARATOR, '"', propertyName, '": ', token)); } else { json.value = string(abi.encodePacked(json.value, '"', propertyName, '": ', token)); } json.depthBitTracker &= MAX_INT256; json.depthBitTracker++; return json; } /** * @dev Writes the end of a JSON array or object based on the token parameter. */ function writeEnd(Json memory json, bytes1 token) private pure returns (Json memory) { json.value = string(abi.encodePacked(json.value, token)); json.depthBitTracker = setListSeparatorFlag(json); if (getCurrentDepth(json) != 0) { json.depthBitTracker--; } return json; } /** * @dev Escapes any characters that required by JSON to be escaped. */ function escapeJsonString(string memory value) private pure returns (string memory str) { bytes memory b = bytes(value); bool foundEscapeChars; for (uint256 i; i < b.length; i++) { if (b[i] == BACKSLASH) { foundEscapeChars = true; break; } else if (b[i] == DOUBLE_QUOTE) { foundEscapeChars = true; break; } else if (b[i] == FRONTSLASH) { foundEscapeChars = true; break; } else if (b[i] == HORIZONTAL_TAB) { foundEscapeChars = true; break; } else if (b[i] == FORM_FEED) { foundEscapeChars = true; break; } else if (b[i] == NEWLINE) { foundEscapeChars = true; break; } else if (b[i] == CARRIAGE_RETURN) { foundEscapeChars = true; break; } else if (b[i] == BACKSPACE) { foundEscapeChars = true; break; } } if (!foundEscapeChars) { return value; } for (uint256 i; i < b.length; i++) { if (b[i] == BACKSLASH) { str = string(abi.encodePacked(str, "\\\\")); } else if (b[i] == DOUBLE_QUOTE) { str = string(abi.encodePacked(str, '\\"')); } else if (b[i] == FRONTSLASH) { str = string(abi.encodePacked(str, "\\/")); } else if (b[i] == HORIZONTAL_TAB) { str = string(abi.encodePacked(str, "\\t")); } else if (b[i] == FORM_FEED) { str = string(abi.encodePacked(str, "\\f")); } else if (b[i] == NEWLINE) { str = string(abi.encodePacked(str, "\\n")); } else if (b[i] == CARRIAGE_RETURN) { str = string(abi.encodePacked(str, "\\r")); } else if (b[i] == BACKSPACE) { str = string(abi.encodePacked(str, "\\b")); } else { str = string(abi.encodePacked(str, b[i])); } } return str; } /** * @dev Tracks the recursive depth of the nested objects / arrays within the JSON text * written so far. This provides the depth of the current token. */ function getCurrentDepth(Json memory json) private pure returns (int256) { return json.depthBitTracker & MAX_INT256; } /** * @dev The highest order bit of json.depthBitTracker is used to discern whether we are writing the first item in a list or not. * if (json.depthBitTracker >> 255) == 1, add a list separator before writing the item * else, no list separator is needed since we are writing the first item. */ function setListSeparatorFlag(Json memory json) private pure returns (int256) { return json.depthBitTracker | (int256(1) << 255); } /** * @dev Converts an address to a string. */ function addressToString(address _address) internal pure returns (string memory) { bytes32 value = bytes32(uint256(uint160(_address))); bytes16 alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = "0"; str[1] = "x"; for (uint256 i; i < 20; i++) { str[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)]; str[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(str); } /** * @dev Converts an int to a string. */ function intToString(int256 i) internal pure returns (string memory) { if (i == 0) { return "0"; } if (i == type(int256).min) { // hard-coded since int256 min value can't be converted to unsigned return "-57896044618658097711785492504343953926634992332820282019728792003956564819968"; } bool negative = i < 0; uint256 len; uint256 j; if(!negative) { j = uint256(i); } else { j = uint256(-i); ++len; // make room for '-' sign } uint256 l = j; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (l != 0) { bstr[--k] = bytes1((48 + uint8(l - (l / 10) * 10))); l /= 10; } if (negative) { bstr[0] = "-"; // prepend '-' } return string(bstr); } /** * @dev Converts a uint to a string. */ function uintToString(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { bstr[--k] = bytes1((48 + uint8(_i - (_i / 10) * 10))); _i /= 10; } return string(bstr); } }
Converts an address to a string./
function addressToString(address _address) internal pure returns (string memory) { bytes32 value = bytes32(uint256(uint160(_address))); bytes16 alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = "0"; str[1] = "x"; for (uint256 i; i < 20; i++) { str[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)]; str[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(str); }
6,369,028
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@keep-network/yearn-vaults/contracts/BaseStrategy.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; /// @notice Interface for the CurveFi pool. /// @dev This is an interface with just a few function signatures of the pool. /// For more info and function description please see: /// https://github.com/curvefi/curve-contract/tree/master/contracts/pool-templates interface ICurvePool { function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external payable; function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns (uint256); } /// @notice Interface for the Convex booster. /// @dev This is an interface with just a few function signatures of the booster. /// For more info and function description please see: /// https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol interface IConvexBooster { function poolInfo(uint256) external view returns ( address lpToken, address convexDepositToken, address curvePoolGauge, address convexRewardPool, address convexExtraRewardStash, bool shutdown ); function deposit( uint256 poolId, uint256 amount, bool stake ) external returns (bool); function earmarkRewards(uint256 poolId) external returns (bool); } /// @notice Interface for the Uniswap v2 router. /// @dev This is an interface with just a few function signatures of the /// router contract. For more info and function description please see: /// https://uniswap.org/docs/v2/smart-contracts/router02 /// This interface allows to interact with Sushiswap as well. interface IUniswapV2Router { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external; function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } /// @notice Interface for the Convex reward pool. /// @dev This is an interface with just a few function signatures of the /// reward pool. For more info and function description please see: /// https://github.com/convex-eth/platform/blob/main/contracts/contracts/BaseRewardPool.sol interface IConvexRewardPool { function balanceOf(address account) external view returns (uint256); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function withdrawAllAndUnwrap(bool claim) external; function getReward(address account, bool claimExtras) external returns (bool); } /// @notice Interface for the Convex extra reward stash. /// @dev This is an interface with just a few function signatures of the extra /// reward stash. For more info and function description please see: /// https://github.com/convex-eth/platform/blob/main/contracts/contracts/ExtraRewardStashV1.sol interface IConvexExtraRewardStash { function tokenInfo() external view returns ( address extraRewardToken, address extraRewardPool, uint256 lastActiveTime ); } /// @notice Interface for the optional metadata functions from the ERC20 standard. interface IERC20Metadata { function symbol() external view returns (string memory); } /// @title ConvexStrategy /// @notice This strategy is meant to be used with the Curve tBTC v2 pool vault. /// The vault's underlying token (a.k.a. want token) should be the LP /// token of the Curve tBTC v2 pool. This strategy borrows the vault's /// underlying token up to the debt limit configured for this strategy /// in the vault. In order to make the profit, the strategy deposits /// the borrowed tokens into the Convex reward pool via the Convex /// booster contract. Depositing tokens in the reward pool generates /// regular CRV and CVX rewards. It can also provide extra rewards /// (denominated in another token) if the Convex reward pool works on /// top of a Curve pool gauge which stakes its deposits into the /// Synthetix staking rewards contract. The financial outcome is settled /// upon a call of the `harvest` method (BaseStrategy.sol). Once that /// call is made, the strategy gets the CRV and CVX rewards from Convex /// reward pool, and claims extra rewards if applicable. Then, it takes /// a small portion of CRV (defined by keepCRV param) and locks it /// into the Curve vote escrow (via CurveYCRVVoter contract) to gain /// CRV boost and increase future gains. Remaining CRV, CVX, and /// optional extra reward tokens are used to buy wBTC via a /// decentralized exchange. At the end, the strategy takes acquired wBTC /// and deposits them to the Curve tBTC v2 pool. This way it obtains new /// LP tokens the vault is interested for, and makes the profit in /// result. At this stage, the strategy may repay some debt back to the /// vault, if needed. The entire cycle repeats for the strategy lifetime /// so all gains are constantly reinvested. Worth to flag that current /// implementation uses wBTC as the intermediary token because /// of its liquidity and ubiquity in BTC-based Curve pools. /// @dev Implementation is based on: /// - General Yearn strategy template /// https://github.com/yearn/brownie-strategy-mix /// - Convex implementation for tBTC v1 vault /// https://github.com/orbxball/btc-curve-convex contract ConvexStrategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /// @notice Governance delay that needs to pass before any parameter change /// initiated by the governance takes effect. uint256 public constant GOVERNANCE_DELAY = 48 hours; uint256 public constant DENOMINATOR = 10000; // Address of the CurveYCRVVoter contract. address public constant voter = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); // Address of the Convex Booster contract. address public constant booster = address(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); // Address of the CRV token contract. address public constant crvToken = address(0xD533a949740bb3306d119CC777fa900bA034cd52); // Address of the Convex CVX token contract. address public constant cvxToken = address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // Address of the WETH token contract. address public constant wethToken = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Address of the WBTC token contract. address public constant wbtcToken = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // Address of the Uniswap V2 router contract. address public constant uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Address of the Sushiswap router contract. address public constant sushiswap = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Address of the depositor contract for the tBTC v2 Curve pool. address public immutable tbtcCurvePoolDepositor; // ID of the Convex reward pool paired with the tBTC v2 Curve pool. uint256 public immutable tbtcConvexRewardPoolId; // Address of the Convex reward pool contract paired with the // tBTC v2 Curve pool. address public immutable tbtcConvexRewardPool; // Address of the extra reward token distributed by the Convex reward pool // paired with the tBTC v2 Curve pool. This is applicable only in case when // the Curve pool's gauge stakes LP tokens into the Synthetix staking // rewards contract (i.e. the gauge is an instance of LiquidityGaugeReward // contract). In such a case, the Convex reward pool wraps the gauge's // additional rewards as Convex extra rewards. This address can be unset if // extra rewards are not distributed by the Convex reward pool. address public tbtcConvexExtraReward; // Determines the portion of CRV tokens which should be locked in the // Curve vote escrow to gain a CRV boost. This is the counter of a fraction // denominated by the DENOMINATOR constant. For example, if the value // is `1000`, that means 10% of tokens will be locked because // 1000/10000 = 0.1 uint256 public keepCRV; uint256 public newKeepCRV; uint256 public keepCRVChangeInitiated; // If extra reward balance is below this threshold, those rewards won't // be sold during prepareReturn method execution. This parameter is here // because extra reward amounts can be to small to exchange them on DEX // immediately and that situation will cause reverts of the prepareReturn // method. Setting that threshold to a non-zero value allows to accumulate // extra rewards to a specific amount which can be sold without troubles. uint256 public extraRewardSwapThreshold; uint256 public newExtraRewardSwapThreshold; uint256 public extraRewardSwapThresholdChangeInitiated; // Determines the slippage tolerance for price-sensitive transactions. // If transaction's slippage is higher, transaction will be reverted. // Default value is 100 basis points (1%). uint256 public slippageTolerance = 100; uint256 public newSlippageTolerance; uint256 public slippageToleranceChangeInitiated; event KeepCRVUpdateStarted(uint256 keepCRV, uint256 timestamp); event KeepCRVUpdated(uint256 keepCRV); event ExtraRewardSwapThresholdUpdateStarted( uint256 extraRewardSwapThreshold, uint256 timestamp ); event ExtraRewardSwapThresholdUpdated(uint256 extraRewardSwapThreshold); event SlippageToleranceUpdateStarted( uint256 slippageTolerance, uint256 timestamp ); event SlippageToleranceUpdated(uint256 slippageTolerance); /// @notice Reverts if called before the governance delay elapses. /// @param changeInitiatedTimestamp Timestamp indicating the beginning /// of the change. modifier onlyAfterGovernanceDelay(uint256 changeInitiatedTimestamp) { require(changeInitiatedTimestamp > 0, "Change not initiated"); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - changeInitiatedTimestamp >= GOVERNANCE_DELAY, "Governance delay has not elapsed" ); _; } constructor( address _vault, address _tbtcCurvePoolDepositor, uint256 _tbtcConvexRewardPoolId ) public BaseStrategy(_vault) { // Strategy settings. minReportDelay = 12 hours; maxReportDelay = 3 days; profitFactor = 1000; debtThreshold = 1e21; keepCRV = 1000; // tBTC-related settings. tbtcCurvePoolDepositor = _tbtcCurvePoolDepositor; tbtcConvexRewardPoolId = _tbtcConvexRewardPoolId; ( address lpToken, , , address rewardPool, address extraRewardStash, ) = IConvexBooster(booster).poolInfo(_tbtcConvexRewardPoolId); require(lpToken == address(want), "Incorrect reward pool LP token"); tbtcConvexRewardPool = rewardPool; if (extraRewardStash != address(0)) { (address extraRewardToken, , ) = IConvexExtraRewardStash( extraRewardStash ).tokenInfo(); if (extraRewardToken != address(0)) { tbtcConvexExtraReward = extraRewardToken; } } } /// @notice Begins the update of the threshold determining the portion of /// CRV tokens which should be locked in the Curve vote escrow to /// gain CRV boost. /// @dev Can be called only by the strategist and governance. /// @param _newKeepCRV Portion as counter of a fraction denominated by the /// DENOMINATOR constant. function beginKeepCRVUpdate(uint256 _newKeepCRV) external onlyAuthorized { require(_newKeepCRV <= DENOMINATOR, "Max value is 10000"); newKeepCRV = _newKeepCRV; keepCRVChangeInitiated = block.timestamp; emit KeepCRVUpdateStarted(_newKeepCRV, block.timestamp); } /// @notice Finalizes the keep CRV threshold update process. /// @dev Can be called only by the strategist and governance, after the /// governance delay elapses. function finalizeKeepCRVUpdate() external onlyAuthorized onlyAfterGovernanceDelay(keepCRVChangeInitiated) { keepCRV = newKeepCRV; emit KeepCRVUpdated(newKeepCRV); keepCRVChangeInitiated = 0; newKeepCRV = 0; } /// @notice Begins the update of the extra reward swap threshold. /// @dev Can be called only by the strategist and governance. /// @param _newExtraRewardSwapThreshold New swap threshold. function beginExtraRewardSwapThresholdUpdate( uint256 _newExtraRewardSwapThreshold ) external onlyAuthorized { newExtraRewardSwapThreshold = _newExtraRewardSwapThreshold; extraRewardSwapThresholdChangeInitiated = block.timestamp; emit ExtraRewardSwapThresholdUpdateStarted( _newExtraRewardSwapThreshold, block.timestamp ); } /// @notice Finalizes the update of the extra reward swap threshold. /// @dev Can be called only by the strategist and governance, after the /// governance delay elapses. function finalizeExtraRewardSwapThresholdUpdate() external onlyAuthorized onlyAfterGovernanceDelay(extraRewardSwapThresholdChangeInitiated) { extraRewardSwapThreshold = newExtraRewardSwapThreshold; emit ExtraRewardSwapThresholdUpdated(newExtraRewardSwapThreshold); extraRewardSwapThresholdChangeInitiated = 0; newExtraRewardSwapThreshold = 0; } /// @notice Begins the update of the slippage tolerance parameter. /// @dev Can be called only by the strategist and governance. /// @param _newSlippageTolerance Slippage tolerance as counter of a fraction /// denominated by the DENOMINATOR constant. function beginSlippageToleranceUpdate(uint256 _newSlippageTolerance) external onlyAuthorized { require(_newSlippageTolerance <= DENOMINATOR, "Max value is 10000"); newSlippageTolerance = _newSlippageTolerance; slippageToleranceChangeInitiated = block.timestamp; emit SlippageToleranceUpdateStarted( _newSlippageTolerance, block.timestamp ); } /// @notice Finalizes the update of the slippage tolerance parameter. /// @dev Can be called only by the strategist and governance, after the the /// governance delay elapses. function finalizeSlippageToleranceUpdate() external onlyAuthorized onlyAfterGovernanceDelay(slippageToleranceChangeInitiated) { slippageTolerance = newSlippageTolerance; emit SlippageToleranceUpdated(newSlippageTolerance); slippageToleranceChangeInitiated = 0; newSlippageTolerance = 0; } /// @return Name of the Yearn vault strategy. function name() external view override returns (string memory) { return string( abi.encodePacked( "Convex", IERC20Metadata(address(want)).symbol() ) ); } /// @return Balance of the vault's underlying token under management. function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } /// @return Balance of the vault's underlying token staked into the Convex /// reward pool. function balanceOfPool() public view returns (uint256) { return IConvexRewardPool(tbtcConvexRewardPool).balanceOf(address(this)); } /// @return Sum of balanceOfWant and balanceOfPool. function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } /// @notice This method is defined in the BaseStrategy contract and is /// meant to perform any adjustments to the core position(s) of this /// strategy, given what change the vault made in the investable /// capital available to the strategy. All free capital in the /// strategy after the report was made is available for reinvestment. /// This strategy implements the aforementioned behavior by taking /// its balance of the vault's underlying token and depositing it to /// the Convex Booster contract. /// @param debtOutstanding Will be 0 if the strategy is not past the /// configured debt limit, otherwise its value will be how far past /// the debt limit the strategy is. The strategy's debt limit is /// configured in the vault. function adjustPosition(uint256 debtOutstanding) internal override { uint256 wantBalance = balanceOfWant(); if (wantBalance > 0) { want.safeIncreaseAllowance(booster, wantBalance); IConvexBooster(booster).deposit( tbtcConvexRewardPoolId, wantBalance, true ); } } /// @notice Withdraws a portion of the vault's underlying token from /// the Convex reward pool. /// @param amount Amount to withdraw. /// @return Amount withdrawn. function withdrawSome(uint256 amount) internal returns (uint256) { amount = Math.min(amount, balanceOfPool()); uint256 initialWantBalance = balanceOfWant(); // Withdraw some vault's underlying tokens but do not claim the rewards // accumulated so far. IConvexRewardPool(tbtcConvexRewardPool).withdrawAndUnwrap( amount, false ); return balanceOfWant().sub(initialWantBalance); } /// @notice This method is defined in the BaseStrategy contract and is meant /// to liquidate up to amountNeeded of want token of this strategy's /// positions, irregardless of slippage. Any excess will be /// re-invested with adjustPosition. This function should return /// the amount of want tokens made available by the liquidation. /// If there is a difference between them, loss indicates whether /// the difference is due to a realized loss, or if there is some /// other situation at play (e.g. locked funds). This strategy /// implements the aforementioned behavior by withdrawing a portion /// of the vault's underlying token (want token) from the Convex /// reward pool. /// @dev The invariant `liquidatedAmount + loss <= amountNeeded` should /// always be maintained. /// @param amountNeeded Amount of the vault's underlying tokens needed by /// the liquidation process. /// @return liquidatedAmount Amount of vault's underlying tokens made /// available by the liquidation. /// @return loss Amount of the loss. function liquidatePosition(uint256 amountNeeded) internal override returns (uint256 liquidatedAmount, uint256 loss) { uint256 wantBalance = balanceOfWant(); if (wantBalance < amountNeeded) { liquidatedAmount = withdrawSome(amountNeeded.sub(wantBalance)); liquidatedAmount = liquidatedAmount.add(wantBalance); loss = amountNeeded.sub(liquidatedAmount); } else { liquidatedAmount = amountNeeded; } } /// @notice This method is defined in the BaseStrategy contract and is meant /// to liquidate everything and return the amount that got freed. /// This strategy implements the aforementioned behavior by withdrawing /// all vault's underlying tokens from the Convex reward pool. /// @dev This function is used during emergency exit instead of prepareReturn /// to liquidate all of the strategy's positions back to the vault. /// @return Total balance of want token held by this strategy. function liquidateAllPositions() internal override returns (uint256) { // Withdraw all vault's underlying tokens from the Convex reward pool. // However, do not claim the rewards accumulated so far because this is // an emergency action and we just focus on recovering all principle // funds, without trying to realize potential gains. IConvexRewardPool(tbtcConvexRewardPool).withdrawAllAndUnwrap(false); // Yearn docs doesn't specify clear enough what exactly should be // returned here. It may be either the total balance after // withdrawAllAndUnwrap or just the amount withdrawn. Currently opting // for the former because of // https://github.com/yearn/yearn-vaults/pull/311#discussion_r625588313. // Also, usage of this result in the harvest method in the BaseStrategy // seems to confirm that. return balanceOfWant(); } /// @notice This method is defined in the BaseStrategy contract and is meant /// to do anything necessary to prepare this strategy for migration, /// such as transferring any reserve or LP tokens, CDPs, or other /// tokens or stores of value. This strategy implements the /// aforementioned behavior by withdrawing all vault's underlying /// tokens from the Convex reward pool, claiming all rewards /// accumulated so far, and transferring those rewards to the new /// strategy. /// @param newStrategy Address of the new strategy meant to replace the /// current one. function prepareMigration(address newStrategy) internal override { // Just withdraw the vault's underlying token from the Convex reward pool. // There is no need to transfer those tokens to the new strategy // right here as this is done in the BaseStrategy's migrate() method. // This call also claims the rewards accumulated so far but they // must be transferred to the new strategy manually. IConvexRewardPool(tbtcConvexRewardPool).withdrawAllAndUnwrap(true); // Transfer all claimed rewards to the new strategy manually. IERC20(crvToken).safeTransfer( newStrategy, IERC20(crvToken).balanceOf(address(this)) ); IERC20(cvxToken).safeTransfer( newStrategy, IERC20(cvxToken).balanceOf(address(this)) ); if (tbtcConvexExtraReward != address(0)) { IERC20(tbtcConvexExtraReward).safeTransfer( newStrategy, IERC20(tbtcConvexExtraReward).balanceOf(address(this)) ); } } /// @notice Takes the keepCRV portion of the CRV balance and transfers /// it to the CurveYCRVVoter contract in order to gain CRV boost. /// @param crvBalance Balance of CRV tokens under management. /// @return Amount of CRV tokens remaining under management after the /// transfer. function adjustCRV(uint256 crvBalance) internal returns (uint256) { uint256 crvTransfer = crvBalance.mul(keepCRV).div(DENOMINATOR); IERC20(crvToken).safeTransfer(voter, crvTransfer); return crvBalance.sub(crvTransfer); } /// @notice This method is defined in the BaseStrategy contract and is meant /// to perform any strategy unwinding or other calls necessary to /// capture the free return this strategy has generated since the /// last time its core position(s) were adjusted. Examples include /// unwrapping extra rewards. This call is only used during normal /// operation of a strategy, and should be optimized to minimize /// losses as much as possible. This strategy implements the /// aforementioned behavior by getting CRV, CVX, and optional extra /// rewards from the Convex reward pool, using obtained tokens to /// buy one of the Curve pool's accepted token, and depositing that /// token back to the Curve pool. This way the strategy is gaining /// new vault's underlying tokens thus making the profit. A small /// portion of CRV rewards (defined by keepCRV param) is transferred /// to the voter contract to increase CRV boost and get more CRV /// rewards in the future. /// @param debtOutstanding Will be 0 if the strategy is not past the /// configured debt limit, otherwise its value will be how far past /// the debt limit the strategy is. The strategy's debt limit is /// configured in the vault. /// @return profit Amount of realized profit. /// @return loss Amount of realized loss. /// @return debtPayment Amount of repaid debt. The value of debtPayment /// should be less than or equal to debtOutstanding. It is okay for /// it to be less than debtOutstanding, as that should only used as /// a guide for how much is left to pay back. Payments should be /// made to minimize loss from slippage, debt, withdrawal fees, etc. function prepareReturn(uint256 debtOutstanding) internal override returns ( uint256 profit, uint256 loss, uint256 debtPayment ) { // Get the initial balance of the vault's underlying token under // strategy management. uint256 initialWantBalance = balanceOfWant(); // Get CRV and CVX rewards from the Convex reward pool. Also, claim // extra rewards if such rewards are distributed by the pool. IConvexRewardPool(tbtcConvexRewardPool).getReward(address(this), true); // Buy WBTC using obtained CRV tokens. uint256 crvBalance = IERC20(crvToken).balanceOf(address(this)); if (crvBalance > 0) { // Deposit a portion of CRV to the voter to gain CRV boost. crvBalance = adjustCRV(crvBalance); IERC20(crvToken).safeIncreaseAllowance(uniswap, crvBalance); address[] memory path = new address[](3); path[0] = crvToken; path[1] = wethToken; path[2] = wbtcToken; IUniswapV2Router(uniswap).swapExactTokensForTokens( crvBalance, minSwapOutAmount(uniswap, crvBalance, path), path, address(this), now ); } // Buy WBTC using obtained CVX tokens. Use SushiSwap as CVX is not // supported by UniSwap. uint256 cvxBalance = IERC20(cvxToken).balanceOf(address(this)); if (cvxBalance > 0) { IERC20(cvxToken).safeIncreaseAllowance(sushiswap, cvxBalance); address[] memory path = new address[](3); path[0] = cvxToken; path[1] = wethToken; path[2] = wbtcToken; IUniswapV2Router(sushiswap).swapExactTokensForTokens( cvxBalance, minSwapOutAmount(sushiswap, cvxBalance, path), path, address(this), now ); } // Buy WBTC using obtained extra reward tokens, if applicable. if (tbtcConvexExtraReward != address(0)) { uint256 extraRewardBalance = IERC20(tbtcConvexExtraReward) .balanceOf(address(this)); if (extraRewardBalance > extraRewardSwapThreshold) { IERC20(tbtcConvexExtraReward).safeIncreaseAllowance( uniswap, extraRewardBalance ); address[] memory path = new address[](3); path[0] = tbtcConvexExtraReward; path[1] = wethToken; path[2] = wbtcToken; IUniswapV2Router(uniswap).swapExactTokensForTokens( extraRewardBalance, minSwapOutAmount(uniswap, extraRewardBalance, path), path, address(this), now ); } } // Deposit acquired WBTC to the Curve pool to gain additional // vault's underlying tokens. uint256 wbtcBalance = IERC20(wbtcToken).balanceOf(address(this)); if (wbtcBalance > 0) { IERC20(wbtcToken).safeIncreaseAllowance( tbtcCurvePoolDepositor, wbtcBalance ); // TODO: When the new curve pool with tBTC v2 is deployed, verify // that the index of wBTC in the array is correct. uint256[4] memory amounts = [0, 0, wbtcBalance, 0]; ICurvePool(tbtcCurvePoolDepositor).add_liquidity( amounts, minLiquidityDepositOutAmount(amounts) ); } // Check the profit and loss in the context of strategy debt. uint256 totalAssets = estimatedTotalAssets(); uint256 totalDebt = vault.strategies(address(this)).totalDebt; if (totalAssets < totalDebt) { loss = totalDebt - totalAssets; profit = 0; } else { profit = balanceOfWant().sub(initialWantBalance); } // Repay some vault debt if needed. if (debtOutstanding > 0) { withdrawSome(debtOutstanding); debtPayment = Math.min( debtOutstanding, balanceOfWant().sub(profit) ); } } /// @notice Calculates the minimum amount of output tokens that must be /// received for the swap transaction not to revert. /// @param dex Address of DEX executing the swap. /// @param amountIn The amount of input tokens to send. /// @param path An array of token addresses determining the swap route. /// @return The minimum amount of output tokens that must be received for /// the swap transaction not to revert. function minSwapOutAmount( address dex, uint256 amountIn, address[] memory path ) internal view returns (uint256) { // Get the maximum possible amount of the output token based on // pair reserves. uint256 amount = IUniswapV2Router(dex).getAmountsOut(amountIn, path)[ path.length - 1 ]; // Include slippage tolerance into the maximum amount of output tokens // in order to obtain the minimum amount desired. return (amount * (DENOMINATOR - slippageTolerance)) / DENOMINATOR; } /// @notice Calculates the minimum amount of LP tokens that must be /// received for the liquidity deposit transaction not to revert. /// @param amountsIn Amounts of each underlying coin being deposited. /// @return The minimum amount of LP tokens that must be received for /// the liquidity deposit transaction not to revert. function minLiquidityDepositOutAmount(uint256[4] memory amountsIn) internal view returns (uint256) { // Get the maximum possible amount of LP tokens received in return // for liquidity deposit based on pool reserves. uint256 amount = ICurvePool(tbtcCurvePoolDepositor).calc_token_amount( amountsIn, true ); // Include slippage tolerance into the maximum amount of LP tokens // in order to obtain the minimum amount desired. return (amount * (DENOMINATOR - slippageTolerance)) / DENOMINATOR; } /// @notice This method is defined in the BaseStrategy contract and is meant /// to define all tokens/tokenized positions this contract manages /// on a persistent basis (e.g. not just for swapping back to /// the want token ephemerally). /// @dev Should not include want token, already included in the base contract. /// @return Addresses of protected tokens function protectedTokens() internal view override returns (address[] memory) { if (tbtcConvexExtraReward != address(0)) { address[] memory protected = new address[](3); protected[0] = crvToken; protected[1] = cvxToken; protected[2] = tbtcConvexExtraReward; return protected; } address[] memory protected = new address[](2); protected[0] = crvToken; protected[1] = cvxToken; return protected; } /// @notice This method is defined in the BaseStrategy contract and is meant /// to provide an accurate conversion from amtInWei (denominated in wei) /// to want token (using the native decimal characteristics of want token). /// @param amtInWei The amount (in wei/1e-18 ETH) to convert to want tokens. /// @return The amount in want tokens. function ethToWant(uint256 amtInWei) public view virtual override returns (uint256) { address[] memory path = new address[](2); path[0] = wethToken; path[1] = wbtcToken; // As of writing this contract, there's no pool available that trades // an underlying token with ETH. To overcome this, the ETH amount // denominated in WEI should be converted into an amount denominated // in one of the tokens accepted by the tBTC v2 Curve pool using Uniswap. // The wBTC token was chosen arbitrarily since it is already used in this // contract for other operations on Uniswap. // amounts[0] -> ETH in wei // amounts[1] -> wBTC uint256[] memory amounts = IUniswapV2Router(uniswap).getAmountsOut( amtInWei, path ); // Use the amount denominated in wBTC to calculate the amount of LP token // (vault's underlying token) that could be obtained if that wBTC amount // was deposited in the Curve pool that has tBTC v2 in it. This way we // obtain an estimated value of the original WEI amount represented in // the vault's underlying token. // // TODO: When the new curve pool with tBTC v2 is deployed, verify that // the index of wBTC (amounts[1]) in the array is correct. return ICurvePool(tbtcCurvePoolDepositor).calc_token_amount( [0, 0, amounts[1], 0], true ); } }
Interface for the Convex booster. This is an interface with just a few function signatures of the booster. For more info and function description please see: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol
interface IConvexBooster { function poolInfo(uint256) external view returns ( address lpToken, address convexDepositToken, address curvePoolGauge, address convexRewardPool, address convexExtraRewardStash, bool shutdown ); function deposit( uint256 poolId, uint256 amount, bool stake ) external returns (bool); function earmarkRewards(uint256 poolId) external returns (bool); }
12,855,652
./full_match/80001/0xBcb019E9ecc34138a51Ae94f95D4686B3C695131/sources/contracts/IndradexBaseVault.sol
Returns the share of 'amount' LP tokens in input tokens with 18 decimals./
function vaultScaledValue(uint256 amount) external view returns(uint256){ return amount.mul(vaultTotalScaledValue()).div(totalSupply()); }
9,458,465
./partial_match/1/0xB2334249a16152C3FB71C3431EBCdAd555130325/sources/SmartMonkeys.sol
Get the first value of a token metadata key. tokenId the token identifier. key the token metadata key./
function _getValue(uint256 tokenId, bytes32 key) internal view returns (bytes memory){ bytes[] memory array = _getValues(tokenId, key); if(array.length > 0){ return array[0]; return ""; } }
9,197,724
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin\upgrades\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, 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. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _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: 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; } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts-ethereum-package\contracts\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: @openzeppelin\contracts-ethereum-package\contracts\access\roles\CapperRole.sol pragma solidity ^0.5.0; contract CapperRole is Initializable, Context { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private _cappers; function initialize(address sender) public initializer { if (!isCapper(sender)) { _addCapper(sender); } } modifier onlyCapper() { require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role"); _; } function isCapper(address account) public view returns (bool) { return _cappers.has(account); } function addCapper(address account) public onlyCapper { _addCapper(account); } function renounceCapper() public { _removeCapper(_msgSender()); } function _addCapper(address account) internal { _cappers.add(account); emit CapperAdded(account); } function _removeCapper(address account) internal { _cappers.remove(account); emit CapperRemoved(account); } uint256[50] private ______gap; } // File: contracts\interfaces\defi\IDefiProtocol.sol pragma solidity ^0.5.12; interface IDefiProtocol { /** * @notice Transfer tokens from sender to DeFi protocol * @param token Address of token * @param amount Value of token to deposit * @return new balances of each token */ function handleDeposit(address token, uint256 amount) external; function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external; /** * @notice Transfer tokens from DeFi protocol to beneficiary * @param token Address of token * @param amount Denormalized value of token to withdraw * @return new balances of each token */ function withdraw(address beneficiary, address token, uint256 amount) external; /** * @notice Transfer tokens from DeFi protocol to beneficiary * @param amounts Array of amounts to withdraw, in order of supportedTokens() * @return new balances of each token */ function withdraw(address beneficiary, uint256[] calldata amounts) external; /** * @notice Claim rewards. Reward tokens will be stored on protocol balance. * @return tokens and their amounts received */ function claimRewards() external returns(address[] memory tokens, uint256[] memory amounts); /** * @notice Withdraw reward tokens to user * @dev called by SavingsModule * @param token Reward token to withdraw * @param user Who should receive tokens * @param amount How many tokens to send */ function withdrawReward(address token, address user, uint256 amount) external; /** * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes */ function balanceOf(address token) external returns(uint256); /** * @notice Balance of all tokens supported by protocol * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes */ function balanceOfAll() external returns(uint256[] memory); /** * @notice Returns optimal proportions of underlying tokens * to prevent fees on deposit/withdrawl if supplying multiple tokens * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes * same as balanceOfAll() */ function optimalProportions() external returns(uint256[] memory); /** * @notice Returns normalized (to USD with 18 decimals) summary balance * of pool using all tokens in this protocol */ function normalizedBalance() external returns(uint256); function supportedTokens() external view returns(address[] memory); function supportedTokensCount() external view returns(uint256); function supportedRewardTokens() external view returns(address[] memory); function isSupportedRewardToken(address token) external view returns(bool); /** * @notice Returns if this protocol can swap all it's normalizedBalance() to specified token */ function canSwapToToken(address token) external view returns(bool); } // File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: contracts\common\Base.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Base is Initializable, Context, Ownable { address constant ZERO_ADDRESS = address(0); function initialize() public initializer { Ownable.initialize(_msgSender()); } } // File: contracts\core\ModuleNames.sol pragma solidity ^0.5.12; /** * @dev List of module names */ contract ModuleNames { // Pool Modules string internal constant MODULE_ACCESS = "access"; string internal constant MODULE_SAVINGS = "savings"; string internal constant MODULE_INVESTING = "investing"; string internal constant MODULE_STAKING = "staking"; string internal constant MODULE_DCA = "dca"; string internal constant MODULE_REWARD = "reward"; // Pool tokens string internal constant TOKEN_AKRO = "akro"; string internal constant TOKEN_ADEL = "adel"; // External Modules (used to store addresses of external contracts) string internal constant CONTRACT_RAY = "ray"; } // File: contracts\common\Module.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Module is Base, ModuleNames { event PoolAddressChanged(address newPool); address public pool; function initialize(address _pool) public initializer { Base.initialize(); setPool(_pool); } function setPool(address _pool) public onlyOwner { require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero"); pool = _pool; emit PoolAddressChanged(_pool); } function getModuleAddress(string memory module) public view returns(address){ require(pool != ZERO_ADDRESS, "Module: no pool"); (bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module)); //Forward error from Pool contract if (!success) assembly { revert(add(result, 32), result) } address moduleAddress = abi.decode(result, (address)); // string memory error = string(abi.encodePacked("Module: requested module not found - ", module)); // require(moduleAddress != ZERO_ADDRESS, error); require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress; } } // File: contracts\interfaces\access\IAccessModule.sol pragma solidity ^0.5.12; interface IAccessModule { enum Operation { Deposit, Withdraw } /** * @notice Check if operation is allowed * @param operation Requested operation * @param sender Sender of transaction */ function isOperationAllowed(Operation operation, address sender) external view returns(bool); } // File: contracts\modules\access\AccessChecker.sol pragma solidity ^0.5.12; contract AccessChecker is Module { modifier operationAllowed(IAccessModule.Operation operation) { IAccessModule am = IAccessModule(getModuleAddress(MODULE_ACCESS)); require(am.isOperationAllowed(operation, _msgSender()), "AccessChecker: operation not allowed"); _; } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "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(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\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 Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @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; } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } // File: contracts\interfaces\token\IPoolTokenBalanceChangeRecipient.sol pragma solidity ^0.5.12; interface IPoolTokenBalanceChangeRecipient { function poolTokenBalanceChanged(address user) external; } // File: contracts\modules\token\DistributionToken.sol pragma solidity ^0.5.12; //solhint-disable func-order contract DistributionToken is ERC20, ERC20Mintable { using SafeMath for uint256; uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60; event DistributionCreated(uint256 amount, uint256 totalSupply); event DistributionsClaimed(address account, uint256 amount, uint256 fromDistribution, uint256 toDistribution); event DistributionAccumulatorIncreased(uint256 amount); struct Distribution { uint256 amount; // Amount of tokens being distributed during the event uint256 totalSupply; // Total supply before distribution } Distribution[] public distributions; // Array of all distributions mapping(address => uint256) public nextDistributions; // Map account to first distribution not yet processed uint256 public nextDistributionTimestamp; //Timestamp when next distribuition should be fired regardles of accumulated tokens uint256 public distributionAccumulator; //Tokens accumulated for next distribution function distribute(uint256 amount) external onlyMinter { distributionAccumulator = distributionAccumulator.add(amount); emit DistributionAccumulatorIncreased(amount); _createDistributionIfReady(); } function createDistribution() external onlyMinter { require(distributionAccumulator > 0, "DistributionToken: nothing to distribute"); _createDistribution(); } function claimDistributions(address account) external returns(uint256) { _createDistributionIfReady(); uint256 amount = _updateUserBalance(account, distributions.length); if (amount > 0) userBalanceChanged(account); return amount; } /** * @notice Claims distributions and allows to specify how many distributions to process. * This allows limit gas usage. * One can do this for others */ function claimDistributions(address account, uint256 toDistribution) external returns(uint256) { require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight"); require(nextDistributions[account] < toDistribution, "DistributionToken: no distributions to claim"); uint256 amount = _updateUserBalance(account, toDistribution); if (amount > 0) userBalanceChanged(account); return amount; } function claimDistributions(address[] calldata accounts) external { _createDistributionIfReady(); for (uint256 i=0; i < accounts.length; i++){ uint256 amount = _updateUserBalance(accounts[i], distributions.length); if (amount > 0) userBalanceChanged(accounts[i]); } } function claimDistributions(address[] calldata accounts, uint256 toDistribution) external { require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight"); for (uint256 i=0; i < accounts.length; i++){ uint256 amount = _updateUserBalance(accounts[i], toDistribution); if (amount > 0) userBalanceChanged(accounts[i]); } } /** * @notice Full balance of account includes: * - balance of tokens account holds himself (0 for addresses of locking contracts) * - balance of tokens locked in contracts * - tokens not yet claimed from distributions */ function fullBalanceOf(address account) public view returns(uint256){ if (account == address(this)) return 0; //Token itself only holds tokens for others uint256 distributionBalance = distributionBalanceOf(account); uint256 unclaimed = calculateClaimAmount(account); return distributionBalance.add(unclaimed); } /** * @notice How many tokens are not yet claimed from distributions * @param account Account to check * @return Amount of tokens available to claim */ function calculateUnclaimedDistributions(address account) public view returns(uint256) { return calculateClaimAmount(account); } /** * @notice Calculates amount of tokens distributed to inital amount between startDistribution and nextDistribution * @param fromDistribution index of first Distribution to start calculations * @param toDistribution index of distribuition next to the last processed * @param initialBalance amount of tokens before startDistribution * @return amount of tokens distributed */ function calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) public view returns(uint256) { require(fromDistribution < toDistribution, "DistributionToken: startDistribution is too high"); require(toDistribution <= distributions.length, "DistributionToken: nextDistribution is too high"); return _calculateDistributedAmount(fromDistribution, toDistribution, initialBalance); } function nextDistribution() public view returns(uint256){ return distributions.length; } /** * @notice Balance of account, which is counted for distributions * It only represents already distributed balance. * @dev This function should be overloaded to include balance of tokens stored in proposals */ function distributionBalanceOf(address account) public view returns(uint256) { return balanceOf(account); } /** * @notice Total supply which is counted for distributions * It only represents already distributed tokens * @dev This function should be overloaded to exclude tokens locked in loans */ function distributionTotalSupply() public view returns(uint256){ return totalSupply(); } // Override functions that change user balance function _transfer(address sender, address recipient, uint256 amount) internal { _createDistributionIfReady(); _updateUserBalance(sender); _updateUserBalance(recipient); super._transfer(sender, recipient, amount); userBalanceChanged(sender); userBalanceChanged(recipient); } function _mint(address account, uint256 amount) internal { _createDistributionIfReady(); _updateUserBalance(account); super._mint(account, amount); userBalanceChanged(account); } function _burn(address account, uint256 amount) internal { _createDistributionIfReady(); _updateUserBalance(account); super._burn(account, amount); userBalanceChanged(account); } function _updateUserBalance(address account) internal returns(uint256) { return _updateUserBalance(account, distributions.length); } function _updateUserBalance(address account, uint256 toDistribution) internal returns(uint256) { uint256 fromDistribution = nextDistributions[account]; if (fromDistribution >= toDistribution) return 0; uint256 distributionAmount = calculateClaimAmount(account, toDistribution); nextDistributions[account] = toDistribution; if (distributionAmount == 0) return 0; super._transfer(address(this), account, distributionAmount); emit DistributionsClaimed(account, distributionAmount, fromDistribution, toDistribution); return distributionAmount; } function _createDistributionIfReady() internal { if (!isReadyForDistribution()) return; _createDistribution(); } function _createDistribution() internal { uint256 currentTotalSupply = distributionTotalSupply(); distributions.push(Distribution({ amount:distributionAccumulator, totalSupply: currentTotalSupply })); super._mint(address(this), distributionAccumulator); //Use super because we overloaded _mint in this contract and need old behaviour emit DistributionCreated(distributionAccumulator, currentTotalSupply); // Clear data for next distribution distributionAccumulator = 0; nextDistributionTimestamp = now.sub(now % DISTRIBUTION_AGGREGATION_PERIOD).add(DISTRIBUTION_AGGREGATION_PERIOD); } /** * @dev This is a placeholder, which may be overrided to notify other contracts of PTK balance change */ function userBalanceChanged(address /*account*/) internal { } /** * @notice Calculates amount of account's tokens to be claimed from distributions */ function calculateClaimAmount(address account) internal view returns(uint256) { if (nextDistributions[account] >= distributions.length) return 0; return calculateClaimAmount(account, distributions.length); } function calculateClaimAmount(address account, uint256 toDistribution) internal view returns(uint256) { assert(toDistribution <= distributions.length); return _calculateDistributedAmount(nextDistributions[account], toDistribution, distributionBalanceOf(account)); } function _calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) internal view returns(uint256) { uint256 next = fromDistribution; uint256 balance = initialBalance; if (initialBalance == 0) return 0; while (next < toDistribution) { uint256 da = balance.mul(distributions[next].amount).div(distributions[next].totalSupply); balance = balance.add(da); next++; } return balance.sub(initialBalance); } /** * @dev Calculates if conditions for creating new distribution are met */ function isReadyForDistribution() internal view returns(bool) { return (distributionAccumulator > 0) && (now >= nextDistributionTimestamp); } } // File: contracts\modules\token\PoolToken.sol pragma solidity ^0.5.12; contract PoolToken is Module, ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, DistributionToken { bool allowTransfers; function initialize(address _pool, string memory poolName, string memory poolSymbol) public initializer { Module.initialize(_pool); ERC20Detailed.initialize(poolName, poolSymbol, 18); ERC20Mintable.initialize(_msgSender()); } function setAllowTransfers(bool _allowTransfers) public onlyOwner { allowTransfers = _allowTransfers; } /** * @dev Overrides ERC20Burnable burnFrom to allow unlimited transfers by SavingsModule */ function burnFrom(address from, uint256 value) public { address savingsModule = getModuleAddress(MODULE_SAVINGS); if (_msgSender() == savingsModule) { //Skip decrease allowance _burn(from, value); }else{ super.burnFrom(from, value); } } function _transfer(address sender, address recipient, uint256 amount) internal { if( !allowTransfers && (sender != address(this)) //transfers from *this* used for distributions ){ revert("PoolToken: transfers between users disabled"); } super._transfer(sender, recipient, amount); } function userBalanceChanged(address account) internal { IPoolTokenBalanceChangeRecipient savings = IPoolTokenBalanceChangeRecipient(getModuleAddress(MODULE_SAVINGS)); savings.poolTokenBalanceChanged(account); } function distributionBalanceOf(address account) public view returns(uint256) { return (account == address(this))?0:super.distributionBalanceOf(account); } function distributionTotalSupply() public view returns(uint256) { return super.distributionTotalSupply().sub(balanceOf(address(this))); } } // File: contracts\modules\savings\RewardDistributions.sol pragma solidity ^0.5.12; contract RewardDistributions is Base, IPoolTokenBalanceChangeRecipient, AccessChecker { event RewardDistribution(address indexed poolToken, address indexed rewardToken, uint256 amount, uint256 totalShares); event RewardWithdraw(address indexed user, address indexed rewardToken, uint256 amount); using SafeERC20 for IERC20; using SafeMath for uint256; struct RewardTokenDistribution { address poolToken; // PoolToken which holders will receive reward uint256 totalShares; // Total shares of PoolToken participating in this distribution address[] rewardTokens; // List of reward tokens being distributed mapping(address=>uint256) amounts; } struct UserProtocolRewards { mapping(address=>uint256) amounts; // Maps address of reward token to amount beeing distributed } struct RewardBalance { uint256 nextDistribution; mapping(address => uint256) shares; // Maps PoolToken to amount of user shares participating in distributions mapping(address => UserProtocolRewards) rewardsByProtocol; //Maps PoolToken to ProtocolRewards struct (map of reward tokens to their balances); } RewardTokenDistribution[] rewardDistributions; mapping(address=>RewardBalance) rewardBalances; //Mapping users to their RewardBalance function poolTokenByProtocol(address _protocol) public view returns(address); function protocolByPoolToken(address _protocol) public view returns(address); function registeredPoolTokens() public view returns(address[] memory); function supportedRewardTokens() public view returns(address[] memory); function poolTokenBalanceChanged(address user) public { address token = _msgSender(); require(isPoolToken(token), "RewardDistributions: PoolToken is not registered"); _updateRewardBalance(user, rewardDistributions.length); uint256 newAmount = PoolToken(token).distributionBalanceOf(user); rewardBalances[user].shares[token] = newAmount; } function withdrawReward() public returns(uint256[] memory) { return withdrawReward(supportedRewardTokens()); } /** * @notice Withdraw reward tokens for user * @param rewardTokens Array of tokens to withdraw */ function withdrawReward(address[] memory rewardTokens) public operationAllowed(IAccessModule.Operation.Withdraw) returns(uint256[] memory) { address user = _msgSender(); uint256[] memory rAmounts = new uint256[](rewardTokens.length); updateRewardBalance(user); for(uint256 i=0; i < rewardTokens.length; i++) { rAmounts[i] = _withdrawReward(user, rewardTokens[i]); } return rAmounts; } // function withdrawReward(address rewardToken) // public operationAllowed(IAccessModule.Operation.Withdraw) // returns(uint256){ // address user = _msgSender(); // updateRewardBalance(user); // return _withdrawReward(user, rewardToken); // } function withdrawReward(address poolToken, address rewardToken) public operationAllowed(IAccessModule.Operation.Withdraw) returns(uint256){ address user = _msgSender(); updateRewardBalance(user); return _withdrawReward(user, poolToken, rewardToken); } // function rewardBalanceOf(address user, address[] memory rewardTokens) public view returns(uint256[] memory) { // uint256[] memory amounts = new uint256[](rewardTokens.length); // address[] memory poolTokens = registeredPoolTokens(); // for(uint256 i=0; i < rewardTokens.length; i++) { // for(uint256 j=0; j < poolTokens.length; j++) { // amounts[i] = amounts[i].add(rewardBalanceOf(user, poolTokens[j], rewardTokens[i])); // } // } // return amounts; // } // function rewardBalanceOf(address user, address poolToken, address[] memory rewardTokens) public view returns(uint256[] memory) { // uint256[] memory amounts = new uint256[](rewardTokens.length); // for(uint256 i=0; i < rewardTokens.length; i++) { // amounts[i] = rewardBalanceOf(user, poolToken, rewardTokens[i]); // } // return amounts; // } function rewardBalanceOf(address user, address poolToken, address rewardToken) public view returns(uint256 amounts) { RewardBalance storage rb = rewardBalances[user]; UserProtocolRewards storage upr = rb.rewardsByProtocol[poolToken]; uint256 balance = upr.amounts[rewardToken]; uint256 next = rb.nextDistribution; while (next < rewardDistributions.length) { RewardTokenDistribution storage d = rewardDistributions[next]; next++; uint256 sh = rb.shares[d.poolToken]; if (sh == 0 || poolToken != d.poolToken) continue; uint256 distrAmount = d.amounts[rewardToken]; balance = balance.add(distrAmount.mul(sh).div(d.totalShares)); } return balance; } /** * @notice Updates user balance * @param user User address */ function updateRewardBalance(address user) public { _updateRewardBalance(user, rewardDistributions.length); } /** * @notice Updates user balance * @param user User address * @param toDistribution Index of distribution next to the last one, which should be processed */ function updateRewardBalance(address user, uint256 toDistribution) public { _updateRewardBalance(user, toDistribution); } function distributeReward(address _protocol) internal { (address[] memory _tokens, uint256[] memory _amounts) = IDefiProtocol(_protocol).claimRewards(); if(_tokens.length > 0) { address poolToken = poolTokenByProtocol(_protocol); distributeReward(poolToken, _tokens, _amounts); } } function storedRewardBalance(address user, address poolToken, address rewardToken) public view returns(uint256 nextDistribution, uint256 poolTokenShares, uint256 storedReward) { RewardBalance storage rb = rewardBalances[user]; nextDistribution = rb.nextDistribution; poolTokenShares = rb.shares[poolToken]; storedReward = rb.rewardsByProtocol[poolToken].amounts[rewardToken]; } function rewardDistribution(uint256 num) public view returns(address poolToken, uint256 totalShares, address[] memory rewardTokens, uint256[] memory amounts){ RewardTokenDistribution storage d = rewardDistributions[num]; poolToken = d.poolToken; totalShares = d.totalShares; rewardTokens = d.rewardTokens; amounts = new uint256[](rewardTokens.length); for(uint256 i=0; i < rewardTokens.length; i++) { address tkn = rewardTokens[i]; amounts[i] = d.amounts[tkn]; } } function rewardDistributionCount() public view returns(uint256){ return rewardDistributions.length; } /** * @notice Create reward distribution */ function distributeReward(address poolToken, address[] memory rewardTokens, uint256[] memory amounts) internal { rewardDistributions.push(RewardTokenDistribution({ poolToken: poolToken, totalShares: PoolToken(poolToken).distributionTotalSupply(), rewardTokens:rewardTokens })); uint256 idx = rewardDistributions.length - 1; RewardTokenDistribution storage rd = rewardDistributions[idx]; for(uint256 i = 0; i < rewardTokens.length; i++) { rd.amounts[rewardTokens[i]] = amounts[i]; emit RewardDistribution(poolToken, rewardTokens[i], amounts[i], rd.totalShares); } } function _withdrawReward(address user, address rewardToken) internal returns(uint256) { address[] memory poolTokens = registeredPoolTokens(); uint256 totalAmount; for(uint256 i=0; i < poolTokens.length; i++) { address poolToken = poolTokens[i]; uint256 amount = rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken]; if(amount > 0){ totalAmount = totalAmount.add(amount); rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken] = 0; IDefiProtocol protocol = IDefiProtocol(protocolByPoolToken(poolToken)); protocol.withdrawReward(rewardToken, user, amount); } } if(totalAmount > 0) { emit RewardWithdraw(user, rewardToken, totalAmount); } return totalAmount; } function _withdrawReward(address user, address poolToken, address rewardToken) internal returns(uint256) { uint256 amount = rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken]; require(amount > 0, "RewardDistributions: nothing to withdraw"); rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken] = 0; IDefiProtocol protocol = IDefiProtocol(protocolByPoolToken(poolToken)); protocol.withdrawReward(rewardToken, user, amount); emit RewardWithdraw(user, rewardToken, amount); return amount; } function _updateRewardBalance(address user, uint256 toDistribution) internal { require(toDistribution <= rewardDistributions.length, "RewardDistributions: toDistribution index is too high"); RewardBalance storage rb = rewardBalances[user]; uint256 next = rb.nextDistribution; if(next >= toDistribution) return; if(next == 0 && rewardDistributions.length > 0){ //This might be a new user, if so we can skip previous distributions address[] memory poolTokens = registeredPoolTokens(); bool hasDeposit; for(uint256 i=0; i< poolTokens.length; i++){ address poolToken = poolTokens[i]; if(rb.shares[poolToken] != 0) { hasDeposit = true; break; } } if(!hasDeposit){ rb.nextDistribution = rewardDistributions.length; return; } } while (next < toDistribution) { RewardTokenDistribution storage d = rewardDistributions[next]; next++; uint256 sh = rb.shares[d.poolToken]; if (sh == 0) continue; UserProtocolRewards storage upr = rb.rewardsByProtocol[d.poolToken]; for (uint256 i=0; i < d.rewardTokens.length; i++) { address rToken = d.rewardTokens[i]; uint256 distrAmount = d.amounts[rToken]; upr.amounts[rToken] = upr.amounts[rToken].add(distrAmount.mul(sh).div(d.totalShares)); } } rb.nextDistribution = next; } function isPoolToken(address token) internal view returns(bool); } // File: contracts\modules\savings\SavingsModule.sol pragma solidity ^0.5.12; contract SavingsModule is Module, AccessChecker, RewardDistributions, CapperRole { uint256 constant MAX_UINT256 = uint256(-1); uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60; event ProtocolRegistered(address protocol, address poolToken); event YieldDistribution(address indexed poolToken, uint256 amount); event DepositToken(address indexed protocol, address indexed token, uint256 dnAmount); event Deposit(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee); event WithdrawToken(address indexed protocol, address indexed token, uint256 dnAmount); event Withdraw(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee); event UserCapEnabledChange(bool enabled); event UserCapChanged(address indexed protocol, address indexed user, uint256 newCap); event DefaultUserCapChanged(address indexed protocol, uint256 newCap); event ProtocolCapEnabledChange(bool enabled); event ProtocolCapChanged(address indexed protocol, uint256 newCap); event VipUserEnabledChange(bool enabled); event VipUserChanged(address indexed protocol, address indexed user, bool isVip); using SafeERC20 for IERC20; using SafeMath for uint256; struct ProtocolInfo { PoolToken poolToken; uint256 previousBalance; uint256 lastRewardDistribution; address[] supportedRewardTokens; mapping(address => uint256) userCap; //Limit of pool tokens which can be minted for a user during deposit uint256 withdrawAllSlippage; //Allowed slippage for withdrawAll function in wei mapping(address=>bool) isVipUser; } struct TokenData { uint8 decimals; } address[] registeredTokens; IDefiProtocol[] registeredProtocols; address[] registeredRewardTokens; mapping(address => TokenData) tokens; mapping(address => ProtocolInfo) protocols; //Mapping of protocol to data we need to calculate APY and do distributions mapping(address => address) poolTokenToProtocol; //Mapping of pool tokens to protocols mapping(address => bool) private rewardTokenRegistered; //marks registered reward tokens bool public userCapEnabled; bool public protocolCapEnabled; mapping(address=>uint256) public defaultUserCap; mapping(address=>uint256) public protocolCap; bool public vipUserEnabled; // Enable VIP user (overrides protocol cap) function initialize(address _pool) public initializer { Module.initialize(_pool); CapperRole.initialize(_msgSender()); } function setUserCapEnabled(bool _userCapEnabled) public onlyCapper { userCapEnabled = _userCapEnabled; emit UserCapEnabledChange(userCapEnabled); } // function setUserCap(address _protocol, address user, uint256 cap) public onlyCapper { // protocols[_protocol].userCap[user] = cap; // emit UserCapChanged(_protocol, user, cap); // } // function setUserCap(address _protocol, address[] calldata users, uint256[] calldata caps) external onlyCapper { // require(users.length == caps.length, "SavingsModule: arrays length not match"); // for(uint256 i=0; i < users.length; i++) { // protocols[_protocol].userCap[users[i]] = caps[i]; // emit UserCapChanged(_protocol, users[i], caps[i]); // } // } function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper { vipUserEnabled = _vipUserEnabled; emit VipUserEnabledChange(_vipUserEnabled); } function setVipUser(address _protocol, address user, bool isVip) public onlyCapper { protocols[_protocol].isVipUser[user] = isVip; emit VipUserChanged(_protocol, user, isVip); } function setDefaultUserCap(address _protocol, uint256 cap) public onlyCapper { defaultUserCap[_protocol] = cap; emit DefaultUserCapChanged(_protocol, cap); } function setProtocolCapEnabled(bool _protocolCapEnabled) public onlyCapper { protocolCapEnabled = _protocolCapEnabled; emit ProtocolCapEnabledChange(protocolCapEnabled); } function setProtocolCap(address _protocol, uint256 cap) public onlyCapper { protocolCap[_protocol] = cap; emit ProtocolCapChanged(_protocol, cap); } function setWithdrawAllSlippage(address _protocol, uint256 slippageWei) public onlyOwner { protocols[_protocol].withdrawAllSlippage = slippageWei; } function registerProtocol(IDefiProtocol protocol, PoolToken poolToken) public onlyOwner { uint256 i; for (i = 0; i < registeredProtocols.length; i++){ if (address(registeredProtocols[i]) == address(protocol)) revert("SavingsModule: protocol already registered"); } registeredProtocols.push(protocol); protocols[address(protocol)] = ProtocolInfo({ poolToken: poolToken, previousBalance: protocol.normalizedBalance(), lastRewardDistribution: 0, supportedRewardTokens: protocol.supportedRewardTokens(), withdrawAllSlippage:0 }); for(i=0; i < protocols[address(protocol)].supportedRewardTokens.length; i++) { address rtkn = protocols[address(protocol)].supportedRewardTokens[i]; if(!rewardTokenRegistered[rtkn]){ rewardTokenRegistered[rtkn] = true; registeredRewardTokens.push(rtkn); } } poolTokenToProtocol[address(poolToken)] = address(protocol); address[] memory supportedTokens = protocol.supportedTokens(); for (i = 0; i < supportedTokens.length; i++) { address tkn = supportedTokens[i]; if (!isTokenRegistered(tkn)){ registeredTokens.push(tkn); tokens[tkn].decimals = ERC20Detailed(tkn).decimals(); } } uint256 normalizedBalance= protocols[address(protocol)].previousBalance; if(normalizedBalance > 0) { uint256 ts = poolToken.totalSupply(); if(ts < normalizedBalance) { poolToken.mint(_msgSender(), normalizedBalance.sub(ts)); } } emit ProtocolRegistered(address(protocol), address(poolToken)); } /** * @notice Only adding reward tokens is correctly supported now (!!!) */ function updateProtocolRewardTokens(IDefiProtocol protocol) public onlyOwner { ProtocolInfo storage pi = protocols[address(protocol)]; pi.supportedRewardTokens = protocol.supportedRewardTokens(); for(uint256 i=0; i < pi.supportedRewardTokens.length; i++) { address rtkn = pi.supportedRewardTokens[i]; if(!rewardTokenRegistered[rtkn]){ rewardTokenRegistered[rtkn] = true; registeredRewardTokens.push(rtkn); } } emit ProtocolRegistered(address(protocol), poolTokenByProtocol(address(protocol))); //TODO: cleanup registeredRewardTokens if reward tokens removed } // function unregisterProtocol(address _protocol) public onlyOwner { // address poolToken = address(protocols[_protocol].poolToken); // delete protocols[_protocol]; // delete poolTokenToProtocol[poolToken]; // address[] memory supportedRewardTokens = IDefiProtocol(_protocol).supportedRewardTokens(); // for(uint256 i=0; i < supportedRewardTokens.length; i++) { // address rtkn = supportedRewardTokens[i]; // //TODO check if this token used by other protocols // rewardTokenRegistered[rtkn] = false; // // Remove reward token from registered array // for(uint256 j=0; j< registeredRewardTokens.length; j++){ // if(registeredRewardTokens[j] == rtkn) { // if(j != registeredRewardTokens.length-1){ // registeredRewardTokens[j] = registeredRewardTokens[registeredRewardTokens.length-1]; // } // registeredRewardTokens.pop(); // } // } // } // } /** * @notice Deposit tokens to several protocols * @param _protocols Array of protocols to deposit tokens (each protocol only once) * @param _tokens Array of tokens to deposit * @param _dnAmounts Array of amounts (denormalized to token decimals) */ function deposit(address[] memory _protocols, address[] memory _tokens, uint256[] memory _dnAmounts) public operationAllowed(IAccessModule.Operation.Deposit) returns(uint256[] memory) { require(_protocols.length == _tokens.length && _tokens.length == _dnAmounts.length, "SavingsModule: size of arrays does not match"); uint256[] memory ptAmounts = new uint256[](_protocols.length); for (uint256 i=0; i < _protocols.length; i++) { address[] memory tkns = new address[](1); tkns[0] = _tokens[i]; uint256[] memory amnts = new uint256[](1); amnts[0] = _dnAmounts[i]; ptAmounts[i] = deposit(_protocols[i], tkns, amnts); } return ptAmounts; } /** * @notice Deposit tokens to a protocol * @param _protocol Protocol to deposit tokens * @param _tokens Array of tokens to deposit * @param _dnAmounts Array of amounts (denormalized to token decimals) */ function deposit(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts) public operationAllowed(IAccessModule.Operation.Deposit) returns(uint256) { //distributeRewardIfRequired(_protocol); uint256 nAmount; for (uint256 i=0; i < _tokens.length; i++) { nAmount = nAmount.add(normalizeTokenAmount(_tokens[i], _dnAmounts[i])); } uint256 nBalanceBefore = distributeYieldInternal(_protocol); depositToProtocol(_protocol, _tokens, _dnAmounts); uint256 nBalanceAfter = updateProtocolBalance(_protocol); PoolToken poolToken = PoolToken(protocols[_protocol].poolToken); uint256 nDeposit = nBalanceAfter.sub(nBalanceBefore); uint256 cap; if(userCapEnabled) { cap = userCap(_protocol, _msgSender()); } uint256 fee; if(nAmount > nDeposit) { fee = nAmount - nDeposit; poolToken.mint(_msgSender(), nDeposit); } else { fee = 0; poolToken.mint(_msgSender(), nAmount); uint256 yield = nDeposit - nAmount; if (yield > 0) { //Additional Yield received from protocol (because of lottery, or something) createYieldDistribution(poolToken, yield); } } if(protocolCapEnabled) { if( !(vipUserEnabled && protocols[_protocol].isVipUser[_msgSender()]) ) { uint256 ptTS = poolToken.totalSupply(); require(ptTS <= protocolCap[_protocol], "SavingsModule: deposit exeeds protocols cap"); } } if(userCapEnabled) { //uint256 actualAmount = nAmount.sub(fee); //Had to remove this because of stack too deep err require(cap >= nAmount.sub(fee), "SavingsModule: deposit exeeds user cap"); // cap = cap - nAmount.sub(fee); //protocols[_protocol].userCap[_msgSender()] = cap; // emit UserCapChanged(_protocol, _msgSender(), cap); } emit Deposit(_protocol, _msgSender(), nAmount, fee); return nDeposit; } function depositToProtocol(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts) internal { require(_tokens.length == _dnAmounts.length, "SavingsModule: count of tokens does not match count of amounts"); for (uint256 i=0; i < _tokens.length; i++) { address tkn = _tokens[i]; IERC20(tkn).safeTransferFrom(_msgSender(), _protocol, _dnAmounts[i]); IDefiProtocol(_protocol).handleDeposit(tkn, _dnAmounts[i]); emit DepositToken(_protocol, tkn, _dnAmounts[i]); } } /** * Withdraw tokens from protocol (all underlying tokens proportiaonally) * @param _protocol Protocol to withdraw from * @param nAmount Normalized (to 18 decimals) amount to withdraw * @return Amount of PoolToken burned from user */ function withdrawAll(address _protocol, uint256 nAmount) public operationAllowed(IAccessModule.Operation.Withdraw) returns(uint256) { //distributeRewardIfRequired(_protocol); PoolToken poolToken = PoolToken(protocols[_protocol].poolToken); uint256 nBalanceBefore = distributeYieldInternal(_protocol); withdrawFromProtocolProportionally(_msgSender(), IDefiProtocol(_protocol), nAmount, nBalanceBefore); uint256 nBalanceAfter = updateProtocolBalance(_protocol); uint256 yield; uint256 actualAmount; if(nBalanceAfter.add(nAmount) > nBalanceBefore) { yield = nBalanceAfter.add(nAmount).sub(nBalanceBefore); actualAmount = nAmount; }else{ actualAmount = nBalanceBefore.sub(nBalanceAfter); require(actualAmount.sub(nAmount) <= protocols[_protocol].withdrawAllSlippage, "SavingsModule: withdrawal fee exeeds slippage"); } // if(userCapEnabled){ // uint256 cap = userCap(_protocol, _msgSender()); // cap = cap.add(actualAmount); // protocols[_protocol].userCap[_msgSender()] = cap; // emit UserCapChanged(_protocol, _msgSender(), cap); // } poolToken.burnFrom(_msgSender(), actualAmount); emit Withdraw(_protocol, _msgSender(), actualAmount, 0); if (yield > 0) { //Additional Yield received from protocol (because of lottery, or something) createYieldDistribution(poolToken, yield); } return actualAmount; } /** * Withdraw token from protocol * @param _protocol Protocol to withdraw from * @param token Token to withdraw * @param dnAmount Amount to withdraw (denormalized) * @param maxNAmount Max amount of PoolToken to burn * @return Amount of PoolToken burned from user */ function withdraw(address _protocol, address token, uint256 dnAmount, uint256 maxNAmount) public operationAllowed(IAccessModule.Operation.Withdraw) returns(uint256){ //distributeRewardIfRequired(_protocol); uint256 nAmount = normalizeTokenAmount(token, dnAmount); uint256 nBalanceBefore = distributeYieldInternal(_protocol); withdrawFromProtocolOne(_msgSender(), IDefiProtocol(_protocol), token, dnAmount); uint256 nBalanceAfter = updateProtocolBalance(_protocol); uint256 yield; uint256 actualAmount; uint256 fee; if(nBalanceAfter.add(nAmount) > nBalanceBefore) { yield = nBalanceAfter.add(nAmount).sub(nBalanceBefore); actualAmount = nAmount; }else{ actualAmount = nBalanceBefore.sub(nBalanceAfter); if (actualAmount > nAmount) fee = actualAmount-nAmount; } require(maxNAmount == 0 || actualAmount <= maxNAmount, "SavingsModule: provided maxNAmount is too low"); // if(userCapEnabled){ // uint256 cap = userCap(_protocol, _msgSender()); // cap = cap.add(actualAmount); // protocols[_protocol].userCap[_msgSender()] = cap; // emit UserCapChanged(_protocol, _msgSender(), cap); // } PoolToken poolToken = PoolToken(protocols[_protocol].poolToken); poolToken.burnFrom(_msgSender(), actualAmount); emit WithdrawToken(_protocol, token, dnAmount); emit Withdraw(_protocol, _msgSender(), actualAmount, fee); if (yield > 0) { //Additional Yield received from protocol (because of lottery, or something) createYieldDistribution(poolToken, yield); } return actualAmount; } /** * @notice Distributes yield. May be called by bot, if there was no deposits/withdrawals */ function distributeYield() public { for(uint256 i=0; i<registeredProtocols.length; i++) { distributeYieldInternal(address(registeredProtocols[i])); } } /** * @notice Distributes reward tokens. May be called by bot, if there was no deposits/withdrawals */ function distributeRewards() public { for(uint256 i=0; i<registeredProtocols.length; i++) { distributeRewardIfRequired(address(registeredProtocols[i])); } } // function distributeRewards(address _protocol) public { // distributeRewardIfRequired(_protocol); // } function distributeRewardsForced(address _protocol) public onlyOwner { ProtocolInfo storage pi = protocols[_protocol]; pi.lastRewardDistribution = now; distributeReward(_protocol); } function userCap(address _protocol, address user) public view returns(uint256) { // uint256 cap = protocols[_protocol].userCap[user]; // if(cap == 0){ // uint256 balance = protocols[_protocol].poolToken.balanceOf(user); // if(balance == 0) cap = defaultUserCap[_protocol]; // } uint256 balance = protocols[_protocol].poolToken.balanceOf(user); uint256 cap; if(balance < defaultUserCap[_protocol]) { cap = defaultUserCap[_protocol] - balance; } return cap; } function isVipUser(address _protocol, address user) view public returns(bool){ return protocols[_protocol].isVipUser[user]; } function poolTokenByProtocol(address _protocol) public view returns(address) { return address(protocols[_protocol].poolToken); } function protocolByPoolToken(address _poolToken) public view returns(address) { return poolTokenToProtocol[_poolToken]; } function rewardTokensByProtocol(address _protocol) public view returns(address[] memory) { return protocols[_protocol].supportedRewardTokens; } function registeredPoolTokens() public view returns(address[] memory poolTokens) { poolTokens = new address[](registeredProtocols.length); for(uint256 i=0; i<poolTokens.length; i++){ poolTokens[i] = address(protocols[address(registeredProtocols[i])].poolToken); } } function supportedProtocols() public view returns(IDefiProtocol[] memory) { return registeredProtocols; } function supportedRewardTokens() public view returns(address[] memory) { return registeredRewardTokens; } function withdrawFromProtocolProportionally(address beneficiary, IDefiProtocol protocol, uint256 nAmount, uint256 currentProtocolBalance) internal { uint256[] memory balances = protocol.balanceOfAll(); uint256[] memory amounts = new uint256[](balances.length); address[] memory _tokens = protocol.supportedTokens(); for (uint256 i = 0; i < amounts.length; i++) { amounts[i] = balances[i].mul(nAmount).div(currentProtocolBalance); emit WithdrawToken(address(protocol), _tokens[i], amounts[i]); } protocol.withdraw(beneficiary, amounts); } function withdrawFromProtocolOne(address beneficiary, IDefiProtocol protocol, address token, uint256 dnAmount) internal { protocol.withdraw(beneficiary, token, dnAmount); } /** * @notice Calculates difference from previous action with a protocol and distributes yield * @dev MUST call this BEFORE deposit/withdraw from protocol * @param _protocol to check * @return Current balance of the protocol */ function distributeYieldInternal(address _protocol) internal returns(uint256){ uint256 currentBalance = IDefiProtocol(_protocol).normalizedBalance(); ProtocolInfo storage pi = protocols[_protocol]; PoolToken poolToken = PoolToken(pi.poolToken); if(currentBalance > pi.previousBalance) { uint256 yield = currentBalance.sub(pi.previousBalance); pi.previousBalance = currentBalance; createYieldDistribution(poolToken, yield); } return currentBalance; } function createYieldDistribution(PoolToken poolToken, uint256 yield) internal { poolToken.distribute(yield); emit YieldDistribution(address(poolToken), yield); } function distributeRewardIfRequired(address _protocol) internal { if(!isRewardDistributionRequired(_protocol)) return; ProtocolInfo storage pi = protocols[_protocol]; pi.lastRewardDistribution = now; distributeReward(_protocol); } /** * @notice Updates balance with result of deposit/withdraw * @dev MUST call this AFTER deposit/withdraw from protocol * @param _protocol to update * @return Current balance of the protocol */ function updateProtocolBalance(address _protocol) internal returns(uint256){ uint256 currentBalance = IDefiProtocol(_protocol).normalizedBalance(); protocols[_protocol].previousBalance = currentBalance; return currentBalance; } function isTokenRegistered(address token) private view returns(bool) { for (uint256 i = 0; i < registeredTokens.length; i++){ if (registeredTokens[i] == token) return true; } return false; } function isPoolToken(address token) internal view returns(bool) { for (uint256 i = 0; i < registeredProtocols.length; i++){ IDefiProtocol protocol = registeredProtocols[i]; if (address(protocols[address(protocol)].poolToken) == token) return true; } return false; } function isRewardDistributionRequired(address _protocol) internal view returns(bool) { return now.sub(protocols[_protocol].lastRewardDistribution) > DISTRIBUTION_AGGREGATION_PERIOD; } function normalizeTokenAmount(address token, uint256 amount) private view returns(uint256) { uint256 decimals = tokens[token].decimals; if (decimals == 18) { return amount; } else if (decimals > 18) { return amount.div(10**(decimals-18)); } else if (decimals < 18) { return amount.mul(10**(18 - decimals)); } } function denormalizeTokenAmount(address token, uint256 amount) private view returns(uint256) { uint256 decimals = tokens[token].decimals; if (decimals == 18) { return amount; } else if (decimals > 18) { return amount.mul(10**(decimals-18)); } else if (decimals < 18) { return amount.div(10**(18 - decimals)); } } } // File: contracts\deploy\InvestingModule.sol pragma solidity ^0.5.12; contract InvestingModule is SavingsModule { function initialize(address _pool) public initializer { SavingsModule.initialize(_pool); } }
Distributes reward tokens. May be called by bot, if there was no deposits/withdrawals/
function distributeRewards() public { for(uint256 i=0; i<registeredProtocols.length; i++) { distributeRewardIfRequired(address(registeredProtocols[i])); } }
33,314
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library PartSetHeader { //struct definition struct Data { uint64 total; bytes hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_total(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_total( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.total = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.hash = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.total != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs); } if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.total); e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.total != 0) { return false; } if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.total = input.total; output.hash = input.hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library PartSetHeader library BlockID { //struct definition struct Data { bytes hash; PartSetHeader.Data part_set_header; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_part_set_header(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_part_set_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (PartSetHeader.Data memory x, uint256 sz) = _decode_PartSetHeader(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.part_set_header = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_PartSetHeader(uint256 p, bytes memory bs) internal pure returns (PartSetHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (PartSetHeader.Data memory r, ) = PartSetHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += PartSetHeader._encode_nested(r.part_set_header, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(PartSetHeader._estimate(r.part_set_header)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; PartSetHeader.store(input.part_set_header, output.part_set_header); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BlockID library Timestamp { //struct definition struct Data { int64 secs; int64 nanos; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_secs(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nanos(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_secs( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.secs = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nanos( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nanos = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.secs != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.secs, pointer, bs); } if (r.nanos != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.nanos, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_int64(r.secs); e += 1 + ProtoBufRuntime._sz_int64(r.nanos); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.secs != 0) { return false; } if (r.nanos != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.secs = input.secs; output.nanos = input.nanos; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Timestamp library Consensus { //struct definition struct Data { uint64 height; uint64 app; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_app(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.height = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_app( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.app = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.height, pointer, bs); } if (r.app != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.app, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.height); e += 1 + ProtoBufRuntime._sz_uint64(r.app); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.height != 0) { return false; } if (r.app != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.height = input.height; output.app = input.app; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Consensus library TmHeader { //struct definition struct Data { Consensus.Data version; string chain_id; int64 height; Timestamp.Data time; BlockID.Data last_block_id; bytes last_commit_hash; bytes data_hash; bytes validators_hash; bytes next_validators_hash; bytes consensus_hash; bytes app_hash; bytes last_results_hash; bytes evidence_hash; bytes proposer_address; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[15] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_version(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_chain_id(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_time(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_last_block_id(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_last_commit_hash(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_data_hash(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_validators_hash(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_next_validators_hash(pointer, bs, r, counters); } else if (fieldId == 10) { pointer += _read_consensus_hash(pointer, bs, r, counters); } else if (fieldId == 11) { pointer += _read_app_hash(pointer, bs, r, counters); } else if (fieldId == 12) { pointer += _read_last_results_hash(pointer, bs, r, counters); } else if (fieldId == 13) { pointer += _read_evidence_hash(pointer, bs, r, counters); } else if (fieldId == 14) { pointer += _read_proposer_address(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_version( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Consensus.Data memory x, uint256 sz) = _decode_Consensus(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.version = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.chain_id = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.height = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_time( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.time = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_block_id( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.last_block_id = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_commit_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.last_commit_hash = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_data_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.data_hash = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.validators_hash = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_next_validators_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.next_validators_hash = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_consensus_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[10] += 1; } else { r.consensus_hash = x; if (counters[10] > 0) counters[10] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_app_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[11] += 1; } else { r.app_hash = x; if (counters[11] > 0) counters[11] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_last_results_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[12] += 1; } else { r.last_results_hash = x; if (counters[12] > 0) counters[12] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_evidence_hash( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[13] += 1; } else { r.evidence_hash = x; if (counters[13] > 0) counters[13] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_proposer_address( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[14] += 1; } else { r.proposer_address = x; if (counters[14] > 0) counters[14] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Consensus(uint256 p, bytes memory bs) internal pure returns (Consensus.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Consensus.Data memory r, ) = Consensus._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Consensus._encode_nested(r.version, pointer, bs); if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.time, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.last_block_id, pointer, bs); if (r.last_commit_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.last_commit_hash, pointer, bs); } if (r.data_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.data_hash, pointer, bs); } if (r.validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validators_hash, pointer, bs); } if (r.next_validators_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.next_validators_hash, pointer, bs); } if (r.consensus_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 10, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.consensus_hash, pointer, bs); } if (r.app_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 11, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.app_hash, pointer, bs); } if (r.last_results_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 12, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.last_results_hash, pointer, bs); } if (r.evidence_hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 13, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.evidence_hash, pointer, bs); } if (r.proposer_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 14, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.proposer_address, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(Consensus._estimate(r.version)); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.time)); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.last_block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(r.last_commit_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.data_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.validators_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.next_validators_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.consensus_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.app_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.last_results_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.evidence_hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.proposer_address.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (bytes(r.chain_id).length != 0) { return false; } if (r.height != 0) { return false; } if (r.last_commit_hash.length != 0) { return false; } if (r.data_hash.length != 0) { return false; } if (r.validators_hash.length != 0) { return false; } if (r.next_validators_hash.length != 0) { return false; } if (r.consensus_hash.length != 0) { return false; } if (r.app_hash.length != 0) { return false; } if (r.last_results_hash.length != 0) { return false; } if (r.evidence_hash.length != 0) { return false; } if (r.proposer_address.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { Consensus.store(input.version, output.version); output.chain_id = input.chain_id; output.height = input.height; Timestamp.store(input.time, output.time); BlockID.store(input.last_block_id, output.last_block_id); output.last_commit_hash = input.last_commit_hash; output.data_hash = input.data_hash; output.validators_hash = input.validators_hash; output.next_validators_hash = input.next_validators_hash; output.consensus_hash = input.consensus_hash; output.app_hash = input.app_hash; output.last_results_hash = input.last_results_hash; output.evidence_hash = input.evidence_hash; output.proposer_address = input.proposer_address; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library TmHeader library Vote { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ; int64 height; int64 round; BlockID.Data block_id; Timestamp.Data timestamp; bytes validator_address; int64 validator_index; bytes signature; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_typ(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_validator_address(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_validator_index(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_signature(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_typ( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp); if (isNil(r)) { counters[1] += 1; } else { r.typ = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.round = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.block_id = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.timestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_address( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.validator_address = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_index( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.validator_index = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.signature = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.typ) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ); pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.block_id, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.validator_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs); } if (r.validator_index != 0) { pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.validator_index, pointer, bs); } if (r.signature.length != 0) { pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ)); e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_int64(r.round); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length); e += 1 + ProtoBufRuntime._sz_int64(r.validator_index); e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.typ) != 0) { return false; } if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (r.validator_address.length != 0) { return false; } if (r.validator_index != 0) { return false; } if (r.signature.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.typ = input.typ; output.height = input.height; output.round = input.round; BlockID.store(input.block_id, output.block_id); Timestamp.store(input.timestamp, output.timestamp); output.validator_address = input.validator_address; output.validator_index = input.validator_index; output.signature = input.signature; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Vote library Commit { //struct definition struct Data { int64 height; int64 round; BlockID.Data block_id; CommitSig.Data[] signatures; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_signatures(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.signatures = new CommitSig.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_height(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_round(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_block_id(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_signatures(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.height = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_int64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.round = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BlockID.Data memory x, uint256 sz) = _decode_BlockID(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.block_id = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signatures( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CommitSig.Data memory x, uint256 sz) = _decode_CommitSig(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.signatures[r.signatures.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BlockID(uint256 p, bytes memory bs) internal pure returns (BlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BlockID.Data memory r, ) = BlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CommitSig(uint256 p, bytes memory bs) internal pure returns (CommitSig.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CommitSig.Data memory r, ) = CommitSig._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BlockID._encode_nested(r.block_id, pointer, bs); if (r.signatures.length != 0) { for(i = 0; i < r.signatures.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CommitSig._encode_nested(r.signatures[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_int64(r.height); e += 1 + ProtoBufRuntime._sz_int64(r.round); e += 1 + ProtoBufRuntime._sz_lendelim(BlockID._estimate(r.block_id)); for(i = 0; i < r.signatures.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CommitSig._estimate(r.signatures[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (r.signatures.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.height = input.height; output.round = input.round; BlockID.store(input.block_id, output.block_id); for(uint256 i4 = 0; i4 < input.signatures.length; i4++) { output.signatures.push(input.signatures[i4]); } } //array helpers for Signatures /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addSignatures(Data memory self, CommitSig.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CommitSig.Data[] memory tmp = new CommitSig.Data[](self.signatures.length + 1); for (uint256 i = 0; i < self.signatures.length; i++) { tmp[i] = self.signatures[i]; } tmp[self.signatures.length] = value; self.signatures = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Commit library CommitSig { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag block_id_flag; bytes validator_address; Timestamp.Data timestamp; bytes signature; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_block_id_flag(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_validator_address(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_signature(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id_flag( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.BlockIDFlag x = TYPES_PROTO_GLOBAL_ENUMS.decode_BlockIDFlag(tmp); if (isNil(r)) { counters[1] += 1; } else { r.block_id_flag = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_validator_address( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.validator_address = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.timestamp = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_signature( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.signature = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.block_id_flag) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_block_id_flag = TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag); pointer += ProtoBufRuntime._encode_enum(_enum_block_id_flag, pointer, bs); } if (r.validator_address.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.validator_address, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (r.signature.length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.signature, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_BlockIDFlag(r.block_id_flag)); e += 1 + ProtoBufRuntime._sz_lendelim(r.validator_address.length); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(r.signature.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.block_id_flag) != 0) { return false; } if (r.validator_address.length != 0) { return false; } if (r.signature.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.block_id_flag = input.block_id_flag; output.validator_address = input.validator_address; Timestamp.store(input.timestamp, output.timestamp); output.signature = input.signature; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitSig library SignedHeader { //struct definition struct Data { TmHeader.Data header; Commit.Data commit; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_header(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_commit(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (TmHeader.Data memory x, uint256 sz) = _decode_TmHeader(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.header = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_commit( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Commit.Data memory x, uint256 sz) = _decode_Commit(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.commit = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_TmHeader(uint256 p, bytes memory bs) internal pure returns (TmHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (TmHeader.Data memory r, ) = TmHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Commit(uint256 p, bytes memory bs) internal pure returns (Commit.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Commit.Data memory r, ) = Commit._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += TmHeader._encode_nested(r.header, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Commit._encode_nested(r.commit, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(TmHeader._estimate(r.header)); e += 1 + ProtoBufRuntime._sz_lendelim(Commit._estimate(r.commit)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { TmHeader.store(input.header, output.header); Commit.store(input.commit, output.commit); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library SignedHeader library CanonicalBlockID { //struct definition struct Data { bytes hash; CanonicalPartSetHeader.Data part_set_header; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_part_set_header(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_part_set_header( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CanonicalPartSetHeader.Data memory x, uint256 sz) = _decode_CanonicalPartSetHeader(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.part_set_header = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CanonicalPartSetHeader(uint256 p, bytes memory bs) internal pure returns (CanonicalPartSetHeader.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CanonicalPartSetHeader.Data memory r, ) = CanonicalPartSetHeader._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CanonicalPartSetHeader._encode_nested(r.part_set_header, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalPartSetHeader._estimate(r.part_set_header)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; CanonicalPartSetHeader.store(input.part_set_header, output.part_set_header); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalBlockID library CanonicalPartSetHeader { //struct definition struct Data { uint64 total; bytes hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_total(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_total( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.total = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.hash = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.total != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.total, pointer, bs); } if (r.hash.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.total); e += 1 + ProtoBufRuntime._sz_lendelim(r.hash.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.total != 0) { return false; } if (r.hash.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.total = input.total; output.hash = input.hash; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalPartSetHeader library CanonicalVote { //struct definition struct Data { TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType typ; int64 height; int64 round; CanonicalBlockID.Data block_id; Timestamp.Data timestamp; string chain_id; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_typ(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_height(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_round(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_block_id(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_timestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_chain_id(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_typ( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); TYPES_PROTO_GLOBAL_ENUMS.SignedMsgType x = TYPES_PROTO_GLOBAL_ENUMS.decode_SignedMsgType(tmp); if (isNil(r)) { counters[1] += 1; } else { r.typ = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_height( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_round( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 x, uint256 sz) = ProtoBufRuntime._decode_sfixed64(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.round = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_block_id( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CanonicalBlockID.Data memory x, uint256 sz) = _decode_CanonicalBlockID(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.block_id = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_timestamp( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Timestamp.Data memory x, uint256 sz) = _decode_Timestamp(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.timestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_chain_id( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.chain_id = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CanonicalBlockID(uint256 p, bytes memory bs) internal pure returns (CanonicalBlockID.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CanonicalBlockID.Data memory r, ) = CanonicalBlockID._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Timestamp(uint256 p, bytes memory bs) internal pure returns (Timestamp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Timestamp.Data memory r, ) = Timestamp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.typ) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_typ = TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ); pointer += ProtoBufRuntime._encode_enum(_enum_typ, pointer, bs); } if (r.height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Fixed64, pointer, bs ); pointer += ProtoBufRuntime._encode_sfixed64(r.height, pointer, bs); } if (r.round != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Fixed64, pointer, bs ); pointer += ProtoBufRuntime._encode_sfixed64(r.round, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CanonicalBlockID._encode_nested(r.block_id, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += Timestamp._encode_nested(r.timestamp, pointer, bs); if (bytes(r.chain_id).length != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_string(r.chain_id, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(TYPES_PROTO_GLOBAL_ENUMS.encode_SignedMsgType(r.typ)); e += 1 + 8; e += 1 + 8; e += 1 + ProtoBufRuntime._sz_lendelim(CanonicalBlockID._estimate(r.block_id)); e += 1 + ProtoBufRuntime._sz_lendelim(Timestamp._estimate(r.timestamp)); e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.chain_id).length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.typ) != 0) { return false; } if (r.height != 0) { return false; } if (r.round != 0) { return false; } if (bytes(r.chain_id).length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.typ = input.typ; output.height = input.height; output.round = input.round; CanonicalBlockID.store(input.block_id, output.block_id); Timestamp.store(input.timestamp, output.timestamp); output.chain_id = input.chain_id; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CanonicalVote library Height { //struct definition struct Data { uint64 revision_number; uint64 revision_height; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_revision_number(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_revision_height(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_revision_number( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.revision_number = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_revision_height( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint64 x, uint256 sz) = ProtoBufRuntime._decode_uint64(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.revision_height = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.revision_number != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.revision_number, pointer, bs); } if (r.revision_height != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_uint64(r.revision_height, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.revision_number); e += 1 + ProtoBufRuntime._sz_uint64(r.revision_height); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.revision_number != 0) { return false; } if (r.revision_height != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.revision_number = input.revision_number; output.revision_height = input.revision_height; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library Height library TYPES_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum BlockIDFlag { BLOCK_ID_FLAG_UNKNOWN, BLOCK_ID_FLAG_ABSENT, BLOCK_ID_FLAG_COMMIT, BLOCK_ID_FLAG_NIL } // Solidity enum encoder function encode_BlockIDFlag(BlockIDFlag x) internal pure returns (int32) { if (x == BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN) { return 0; } if (x == BlockIDFlag.BLOCK_ID_FLAG_ABSENT) { return 1; } if (x == BlockIDFlag.BLOCK_ID_FLAG_COMMIT) { return 2; } if (x == BlockIDFlag.BLOCK_ID_FLAG_NIL) { return 3; } revert(); } // Solidity enum decoder function decode_BlockIDFlag(int64 x) internal pure returns (BlockIDFlag) { if (x == 0) { return BlockIDFlag.BLOCK_ID_FLAG_UNKNOWN; } if (x == 1) { return BlockIDFlag.BLOCK_ID_FLAG_ABSENT; } if (x == 2) { return BlockIDFlag.BLOCK_ID_FLAG_COMMIT; } if (x == 3) { return BlockIDFlag.BLOCK_ID_FLAG_NIL; } revert(); } // Solidity enum definitions enum SignedMsgType { SIGNED_MSG_TYPE_UNKNOWN, SIGNED_MSG_TYPE_PREVOTE, SIGNED_MSG_TYPE_PRECOMMIT, SIGNED_MSG_TYPE_PROPOSAL } // Solidity enum encoder function encode_SignedMsgType(SignedMsgType x) internal pure returns (int32) { if (x == SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN) { return 0; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PREVOTE) { return 1; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT) { return 2; } if (x == SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL) { return 32; } revert(); } // Solidity enum decoder function decode_SignedMsgType(int64 x) internal pure returns (SignedMsgType) { if (x == 0) { return SignedMsgType.SIGNED_MSG_TYPE_UNKNOWN; } if (x == 1) { return SignedMsgType.SIGNED_MSG_TYPE_PREVOTE; } if (x == 2) { return SignedMsgType.SIGNED_MSG_TYPE_PRECOMMIT; } if (x == 32) { return SignedMsgType.SIGNED_MSG_TYPE_PROPOSAL; } revert(); } } //library TYPES_PROTO_GLOBAL_ENUMS
The estimator for a struct r The struct to be encoded return The number of bytes encoded in estimation/
function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_uint64(r.height); e += 1 + ProtoBufRuntime._sz_uint64(r.app); return e; }
2,568,191
pragma solidity ^0.4.18; import './IFinancieNotifier.sol'; import './FinancieCoreComponents.sol'; import '../utility/Utils.sol'; contract FinancieNotifier is IFinancieNotifier, FinancieCoreComponents, Utils { address latest; event ActivateUser(address indexed _sender, uint32 indexed _userId, uint _timestamp); event ApproveNewCards(address indexed _card, uint _timestamp); event CardAuctionFinalized(address indexed _card, address indexed _auction, uint _timestamp); event ApproveNewBancor(address indexed _card, address indexed _bancor, uint _timestamp); event Log(address indexed _sender, address indexed _target, EventType indexed _eventType, address _from, address _to, uint256 _paidAmount, uint256 _receivedAmount, uint _timestamp); event AddOwnedCardList(address indexed _sender, address indexed _address, uint _timestamp); event AddOwnedTicketList(address indexed _sender, address indexed _ticket, uint _timestamp); event AddPaidTicketList(address indexed _sender, address indexed _ticket, uint256 _amount, uint _timestamp); event ConvertCards(address indexed _sender, address indexed _from, address indexed _to, uint256 _amountFrom, uint256 _amountTo, uint _timestamp); event BidCards(address indexed _sender, address indexed _to, uint256 _amount, uint _timestamp); event WithdrawalCards(address indexed _sender, address indexed _to, uint256 _bids, uint256 _amount, uint _timestamp); event BurnCards(address indexed _sender, address indexed _card, uint256 _amount, uint _timestamp); event BurnTickets(address indexed _sender, address indexed _ticket, uint256 _amount, uint _timestamp); event AuctionRevenue(address _sender, address indexed _target, address indexed _card, address indexed _receiver, uint256 _amount, uint _timestamp); event ExchangeRevenue(address _sender, address indexed _target, address indexed _card, address indexed _receiver, uint256 _amount, uint _timestamp); constructor(address _managedContracts, address _platformToken, address _ether_token) public FinancieCoreComponents(_managedContracts, _platformToken, _ether_token) { latest = address(this); } modifier sameOwner { assert(msg.sender == owner || IOwned(msg.sender).owner() == owner); _; } /** * @notice Set latest notifier */ function setLatestNotifier(address _latest) public sameOwner { latest = _latest; } /** * @notice returns latest notifier and update itself if expired */ function latestNotifier() public returns (address) { // this contract is latest if ( latest == address(this) ) { return latest; } // up to date? address _latest = IFinancieNotifier(latest).latestNotifier(); if ( latest == _latest ) { return latest; } // update and return latest = _latest; return latest; } /** * @notice To prevent receiving ether */ function() payable public { revert(); } /** * */ function activateUser(uint32 _userId) public greaterThanZero(_userId) { emit ActivateUser(msg.sender, _userId, now); } /** * */ function notifyApproveNewCards(address _card) public sameOwner { emit ApproveNewCards(_card, now); } /** * */ function notifyCardAuctionFinalized(address _card, address _auction) public sameOwner { emit CardAuctionFinalized(_card, _auction, now); } /** * */ function notifyApproveNewBancor(address _card, address _bancor) public sameOwner { emit ApproveNewBancor(_card, _bancor, now); } /** * @notice log the purchase of ticket */ function notifyPurchaseTickets(address _sender, address _card, address _ticket, uint256 _price, uint256 _amount) public sameOwner { emit AddOwnedTicketList(_sender, _ticket, now); emit Log( _sender, msg.sender, EventType.BuyTicket, _card, _ticket, _price, _amount, now); } /** * @notice log the burn of tickets */ function notifyBurnTickets(address _sender, uint256 _amount) public sameOwner { emit AddPaidTicketList(_sender, msg.sender, _amount, now); emit Log( _sender, msg.sender, EventType.BurnTicket, msg.sender, 0x0, _amount, 0, now); emit BurnTickets(_sender, msg.sender, _amount, now); } function notifyConvertCards( address _sender, address _from, address _to, uint256 _amountFrom, uint256 _amountTo) public sameOwner { if ( _to == address(etherToken) ) { emit Log( _sender, msg.sender, EventType.SellCards, _from, _to, _amountFrom, _amountTo, now); } else { emit Log( _sender, msg.sender, EventType.BuyCards, _from, _to, _amountFrom, _amountTo, now); emit AddOwnedCardList(_sender, _to, now); } emit ConvertCards(_sender, _from, _to, _amountFrom, _amountTo, now); } /** * @notice log the bid of cards for sales contract */ function notifyBidCards(address _sender, address _to, uint256 _amount) public sameOwner { emit Log( _sender, msg.sender, EventType.BidCards, etherToken, _to, _amount, 0, now); emit BidCards(_sender, _to, _amount, now); } /** * @notice log the withdrawal of cards from sales contract */ function notifyWithdrawalCards(address _sender, address _to, uint256 _bids, uint256 _amount) public sameOwner { emit AddOwnedCardList(_sender, _to, now); emit Log( _sender, msg.sender, EventType.WithdrawCards, 0x0, _to, 0, _amount, now); emit WithdrawalCards(_sender, _to, _bids, _amount, now); } /** * @notice log the burn of cards */ function notifyBurnCards(address _sender, uint256 _amount) public sameOwner { emit Log( _sender, msg.sender, EventType.BurnCards, msg.sender, 0x0, _amount, 0, now); emit BurnCards(msg.sender, msg.sender, _amount, now); } /** * @notice log the revenue of auction */ function notifyAuctionRevenue( address _sender, address _target, address _card, address _hero, uint256 _hero_amount, address _team, uint256 _team_amount) public sameOwner { emit AuctionRevenue(_sender, _target, _card, _hero, _hero_amount, now); emit AuctionRevenue(_sender, _target, _card, _team, _team_amount, now); } /** * @notice log the revenue of exchange */ function notifyExchangeRevenue( address _sender, address _target, address _card, address _hero, uint256 _hero_amount, address _team, uint256 _team_amount) public sameOwner { emit ExchangeRevenue(_sender, _target, _card, _hero, _hero_amount, now); emit ExchangeRevenue(_sender, _target, _card, _team, _team_amount, now); } }
log the revenue of exchange/
function notifyExchangeRevenue( address _sender, address _target, address _card, address _hero, uint256 _hero_amount, address _team, uint256 _team_amount) public sameOwner { emit ExchangeRevenue(_sender, _target, _card, _hero, _hero_amount, now); emit ExchangeRevenue(_sender, _target, _card, _team, _team_amount, now); }
13,000,915
./partial_match/1/0x79AC8cE2991F642612ABd48EB69047adA1F2B2B1/sources/GardenContractV2.sol
========== RESTRICTED FUNCTIONS ========== /
function addOwner(address _newOwner) external isAnOwner { addOwnerShip(_newOwner); }
2,697,045
./full_match/97/0xF8630744431244dc749c6D52b300C1f134c66547/sources/project_/contracts/Crowdsale.sol
return unused ETH deduct non ETH token from user
function userDeposit (uint256 _amount, address _baseToken) external payable nonReentrant { if (STATUS.whitelistOnly) { require(WHITELIST.contains(_msgSender()), 'NOT WHITELISTED'); } bool isETH = _baseToken == address(0); if(isETH) { require(INFO.withETH, "NOT ALLOWED TO PARTICIPATE WITH ETH"); require(_isValidBaseToken(_baseToken), "INVALID BASE TOKEN"); } uint256 ethPrice = getETHPrice(); BuyerInfo storage buyer = BUYERS[msg.sender]; uint256 amount_in = isETH ? msg.value : _amount; uint256 allowance = INFO.maxSpendPerBuyer.sub(buyer.depositedValue); uint256 _totalCollected = getTotalCollectedValue(); uint256 remaining = INFO.hardcap.sub(_totalCollected); allowance = allowance > remaining ? remaining : allowance; if (amount_in > allowance) { amount_in = allowance; } uint256 tokensSold = isETH ? amount_in.mul(ethPrice).mul(10 ** PRICE_DECIMALS).div(INFO.tokenPrice).div(10 ** 18) : amount_in.mul(10 ** PRICE_DECIMALS).div(INFO.tokenPrice).div(10 ** uint256(IERC20(_baseToken).decimals())); require(tokensSold > 0, 'ZERO TOKENS'); if (buyer.depositedValue == 0) { STATUS.numBuyers++; } if(isETH) { buyer.ethDeposited = buyer.ethDeposited.add(amount_in); buyer.depositedValue = buyer.depositedValue.add(amount_in.mul(ethPrice)); STATUS.totalETHCollected = STATUS.totalETHCollected.add(amount_in); STATUS.totalETHValueCollected = STATUS.totalETHValueCollected.add(amount_in.mul(ethPrice)); buyer.baseDeposited[_baseToken] = buyer.baseDeposited[_baseToken].add(amount_in); buyer.depositedValue = buyer.depositedValue.add(amount_in); STATUS.totalBaseCollected[_baseToken] = STATUS.totalBaseCollected[_baseToken].add(amount_in); } buyer.tokensOwed = buyer.tokensOwed.add(tokensSold); STATUS.totalTokensSold = STATUS.totalTokensSold.add(tokensSold); if (isETH && amount_in < msg.value) { msg.sender.transfer(msg.value.sub(amount_in)); } if (!isETH) { TransferHelper.safeTransferFrom(_baseToken, msg.sender, address(this), amount_in); } }
5,027,387
pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./libs/DecMath.sol"; import "./moneymarkets/IMoneyMarket.sol"; import "./models/fee/IFeeModel.sol"; import "./models/interest/IInterestModel.sol"; import "./NFT.sol"; import "./rewards/MPHMinter.sol"; import "./models/interest-oracle/IInterestOracle.sol"; // DeLorean Interest -- It's coming back from the future! // EL PSY CONGROO // Author: Zefram Lou // Contact: zefram@baconlabs.dev contract DInterest is ReentrancyGuard, Ownable { using SafeMath for uint256; using DecMath for uint256; using SafeERC20 for ERC20; using Address for address; // Constants uint256 internal constant PRECISION = 10**18; uint256 internal constant ONE = 10**18; uint256 internal constant EXTRA_PRECISION = 10**27; // used for sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex // User deposit data // Each deposit has an ID used in the depositNFT, which is equal to its index in `deposits` plus 1 struct Deposit { uint256 amount; // Amount of stablecoin deposited uint256 maturationTimestamp; // Unix timestamp after which the deposit may be withdrawn, in seconds uint256 interestOwed; // Deficit incurred to the pool at time of deposit uint256 initialMoneyMarketIncomeIndex; // Money market's income index at time of deposit bool active; // True if not yet withdrawn, false if withdrawn bool finalSurplusIsNegative; uint256 finalSurplusAmount; // Surplus remaining after withdrawal uint256 mintMPHAmount; // Amount of MPH minted to user uint256 depositTimestamp; // Unix timestamp at time of deposit, in seconds } Deposit[] internal deposits; uint256 public latestFundedDepositID; // the ID of the most recently created deposit that was funded uint256 public unfundedUserDepositAmount; // the deposited stablecoin amount (plus interest owed) whose deficit hasn't been funded // Funding data // Each funding has an ID used in the fundingNFT, which is equal to its index in `fundingList` plus 1 struct Funding { // deposits with fromDepositID < ID <= toDepositID are funded uint256 fromDepositID; uint256 toDepositID; uint256 recordedFundedDepositAmount; // the current stablecoin amount earning interest for the funder uint256 recordedMoneyMarketIncomeIndex; // the income index at the last update (creation or withdrawal) uint256 creationTimestamp; // Unix timestamp at time of deposit, in seconds } Funding[] internal fundingList; // the sum of (recordedFundedDepositAmount / recordedMoneyMarketIncomeIndex) of all fundings uint256 public sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex; // Params uint256 public MinDepositPeriod; // Minimum deposit period, in seconds uint256 public MaxDepositPeriod; // Maximum deposit period, in seconds uint256 public MinDepositAmount; // Minimum deposit amount for each deposit, in stablecoins uint256 public MaxDepositAmount; // Maximum deposit amount for each deposit, in stablecoins // Instance variables uint256 public totalDeposit; uint256 public totalInterestOwed; // External smart contracts IMoneyMarket public moneyMarket; ERC20 public stablecoin; IFeeModel public feeModel; IInterestModel public interestModel; IInterestOracle public interestOracle; NFT public depositNFT; NFT public fundingNFT; MPHMinter public mphMinter; // Events event EDeposit( address indexed sender, uint256 indexed depositID, uint256 amount, uint256 maturationTimestamp, uint256 interestAmount, uint256 mintMPHAmount ); event EWithdraw( address indexed sender, uint256 indexed depositID, uint256 indexed fundingID, bool early, uint256 takeBackMPHAmount ); event EFund( address indexed sender, uint256 indexed fundingID, uint256 deficitAmount ); event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); event ESetParamUint( address indexed sender, string indexed paramName, uint256 newValue ); struct DepositLimit { uint256 MinDepositPeriod; uint256 MaxDepositPeriod; uint256 MinDepositAmount; uint256 MaxDepositAmount; } constructor( DepositLimit memory _depositLimit, address _moneyMarket, // Address of IMoneyMarket that's used for generating interest (owner must be set to this DInterest contract) address _stablecoin, // Address of the stablecoin used to store funds address _feeModel, // Address of the FeeModel contract that determines how fees are charged address _interestModel, // Address of the InterestModel contract that determines how much interest to offer address _interestOracle, // Address of the InterestOracle contract that provides the average interest rate address _depositNFT, // Address of the NFT representing ownership of deposits (owner must be set to this DInterest contract) address _fundingNFT, // Address of the NFT representing ownership of fundings (owner must be set to this DInterest contract) address _mphMinter // Address of the contract for handling minting MPH to users ) public { // Verify input addresses require( _moneyMarket.isContract() && _stablecoin.isContract() && _feeModel.isContract() && _interestModel.isContract() && _interestOracle.isContract() && _depositNFT.isContract() && _fundingNFT.isContract() && _mphMinter.isContract(), "DInterest: An input address is not a contract" ); moneyMarket = IMoneyMarket(_moneyMarket); stablecoin = ERC20(_stablecoin); feeModel = IFeeModel(_feeModel); interestModel = IInterestModel(_interestModel); interestOracle = IInterestOracle(_interestOracle); depositNFT = NFT(_depositNFT); fundingNFT = NFT(_fundingNFT); mphMinter = MPHMinter(_mphMinter); // Ensure moneyMarket uses the same stablecoin require( moneyMarket.stablecoin() == _stablecoin, "DInterest: moneyMarket.stablecoin() != _stablecoin" ); // Ensure interestOracle uses the same moneyMarket require( interestOracle.moneyMarket() == _moneyMarket, "DInterest: interestOracle.moneyMarket() != _moneyMarket" ); // Verify input uint256 parameters require( _depositLimit.MaxDepositPeriod > 0 && _depositLimit.MaxDepositAmount > 0, "DInterest: An input uint256 is 0" ); require( _depositLimit.MinDepositPeriod <= _depositLimit.MaxDepositPeriod, "DInterest: Invalid DepositPeriod range" ); require( _depositLimit.MinDepositAmount <= _depositLimit.MaxDepositAmount, "DInterest: Invalid DepositAmount range" ); MinDepositPeriod = _depositLimit.MinDepositPeriod; MaxDepositPeriod = _depositLimit.MaxDepositPeriod; MinDepositAmount = _depositLimit.MinDepositAmount; MaxDepositAmount = _depositLimit.MaxDepositAmount; totalDeposit = 0; } /** Public actions */ function deposit(uint256 amount, uint256 maturationTimestamp) external nonReentrant { _deposit(amount, maturationTimestamp); } function withdraw(uint256 depositID, uint256 fundingID) external nonReentrant { _withdraw(depositID, fundingID, false); } function earlyWithdraw(uint256 depositID, uint256 fundingID) external nonReentrant { _withdraw(depositID, fundingID, true); } function multiDeposit( uint256[] calldata amountList, uint256[] calldata maturationTimestampList ) external nonReentrant { require( amountList.length == maturationTimestampList.length, "DInterest: List lengths unequal" ); for (uint256 i = 0; i < amountList.length; i = i.add(1)) { _deposit(amountList[i], maturationTimestampList[i]); } } function multiWithdraw( uint256[] calldata depositIDList, uint256[] calldata fundingIDList ) external nonReentrant { require( depositIDList.length == fundingIDList.length, "DInterest: List lengths unequal" ); for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) { _withdraw(depositIDList[i], fundingIDList[i], false); } } function multiEarlyWithdraw( uint256[] calldata depositIDList, uint256[] calldata fundingIDList ) external nonReentrant { require( depositIDList.length == fundingIDList.length, "DInterest: List lengths unequal" ); for (uint256 i = 0; i < depositIDList.length; i = i.add(1)) { _withdraw(depositIDList[i], fundingIDList[i], true); } } /** Deficit funding */ function fundAll() external nonReentrant { // Calculate current deficit (bool isNegative, uint256 deficit) = surplus(); require(isNegative, "DInterest: No deficit available"); require( !depositIsFunded(deposits.length), "DInterest: All deposits funded" ); // Create funding struct uint256 incomeIndex = moneyMarket.incomeIndex(); require(incomeIndex > 0, "DInterest: incomeIndex == 0"); fundingList.push( Funding({ fromDepositID: latestFundedDepositID, toDepositID: deposits.length, recordedFundedDepositAmount: unfundedUserDepositAmount, recordedMoneyMarketIncomeIndex: incomeIndex, creationTimestamp: now }) ); // Update relevant values sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex .add( unfundedUserDepositAmount.mul(EXTRA_PRECISION).div(incomeIndex) ); latestFundedDepositID = deposits.length; unfundedUserDepositAmount = 0; _fund(deficit); } function fundMultiple(uint256 toDepositID) external nonReentrant { require( toDepositID > latestFundedDepositID, "DInterest: Deposits already funded" ); require( toDepositID <= deposits.length, "DInterest: Invalid toDepositID" ); (bool isNegative, uint256 surplus) = surplus(); require(isNegative, "DInterest: No deficit available"); uint256 totalDeficit = 0; uint256 totalSurplus = 0; uint256 totalDepositAndInterestToFund = 0; // Deposits with ID [latestFundedDepositID+1, toDepositID] will be funded for ( uint256 id = latestFundedDepositID.add(1); id <= toDepositID; id = id.add(1) ) { Deposit storage depositEntry = _getDeposit(id); if (depositEntry.active) { // Deposit still active, use current surplus (isNegative, surplus) = surplusOfDeposit(id); } else { // Deposit has been withdrawn, use recorded final surplus (isNegative, surplus) = ( depositEntry.finalSurplusIsNegative, depositEntry.finalSurplusAmount ); } if (isNegative) { // Add on deficit to total totalDeficit = totalDeficit.add(surplus); } else { // Has surplus totalSurplus = totalSurplus.add(surplus); } if (depositEntry.active) { totalDepositAndInterestToFund = totalDepositAndInterestToFund .add(depositEntry.amount) .add(depositEntry.interestOwed); } } if (totalSurplus >= totalDeficit) { // Deposits selected have a surplus as a whole, revert revert("DInterest: Selected deposits in surplus"); } else { // Deduct surplus from totalDeficit totalDeficit = totalDeficit.sub(totalSurplus); } // Create funding struct uint256 incomeIndex = moneyMarket.incomeIndex(); require(incomeIndex > 0, "DInterest: incomeIndex == 0"); fundingList.push( Funding({ fromDepositID: latestFundedDepositID, toDepositID: toDepositID, recordedFundedDepositAmount: totalDepositAndInterestToFund, recordedMoneyMarketIncomeIndex: incomeIndex, creationTimestamp: now }) ); // Update relevant values sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex .add( totalDepositAndInterestToFund.mul(EXTRA_PRECISION).div(incomeIndex) ); latestFundedDepositID = toDepositID; unfundedUserDepositAmount = unfundedUserDepositAmount.sub( totalDepositAndInterestToFund ); _fund(totalDeficit); } function payInterestToFunder(uint256 fundingID) external returns (uint256 interestAmount) { address funder = fundingNFT.ownerOf(fundingID); require(funder == msg.sender, "DInterest: not funder"); Funding storage f = _getFunding(fundingID); uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex(); interestAmount = f .recordedFundedDepositAmount .mul(currentMoneyMarketIncomeIndex) .div(f.recordedMoneyMarketIncomeIndex) .sub(f.recordedFundedDepositAmount); // Update funding values sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex .sub( f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div( f.recordedMoneyMarketIncomeIndex ) ); f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex; sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex .add( f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div( f.recordedMoneyMarketIncomeIndex ) ); // Send interest to funder if (interestAmount > 0) { interestAmount = moneyMarket.withdraw(interestAmount); if (interestAmount > 0) { stablecoin.safeTransfer(funder, interestAmount); } } } /** Public getters */ function calculateInterestAmount( uint256 depositAmount, uint256 depositPeriodInSeconds ) public returns (uint256 interestAmount) { (, uint256 moneyMarketInterestRatePerSecond) = interestOracle.updateAndQuery(); (bool surplusIsNegative, uint256 surplusAmount) = surplus(); return interestModel.calculateInterestAmount( depositAmount, depositPeriodInSeconds, moneyMarketInterestRatePerSecond, surplusIsNegative, surplusAmount ); } /** @notice Computes the floating interest amount owed to deficit funders, which will be paid out when a funded deposit is withdrawn. Formula: \sum_i recordedFundedDepositAmount_i * (incomeIndex / recordedMoneyMarketIncomeIndex_i - 1) = incomeIndex * (\sum_i recordedFundedDepositAmount_i / recordedMoneyMarketIncomeIndex_i) - (totalDeposit + totalInterestOwed - unfundedUserDepositAmount) where i refers to a funding */ function totalInterestOwedToFunders() public returns (uint256 interestOwed) { uint256 currentValue = moneyMarket .incomeIndex() .mul( sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex ) .div(EXTRA_PRECISION); uint256 initialValue = totalDeposit.add(totalInterestOwed).sub(unfundedUserDepositAmount); if (currentValue < initialValue) { return 0; } return currentValue.sub(initialValue); } function surplus() public returns (bool isNegative, uint256 surplusAmount) { uint256 totalValue = moneyMarket.totalValue(); uint256 totalOwed = totalDeposit.add(totalInterestOwed).add( totalInterestOwedToFunders() ); if (totalValue >= totalOwed) { // Locked value more than owed deposits, positive surplus isNegative = false; surplusAmount = totalValue.sub(totalOwed); } else { // Locked value less than owed deposits, negative surplus isNegative = true; surplusAmount = totalOwed.sub(totalValue); } } function surplusOfDeposit(uint256 depositID) public returns (bool isNegative, uint256 surplusAmount) { Deposit storage depositEntry = _getDeposit(depositID); uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex(); uint256 currentDepositValue = depositEntry.amount.mul(currentMoneyMarketIncomeIndex).div( depositEntry.initialMoneyMarketIncomeIndex ); uint256 owed = depositEntry.amount.add(depositEntry.interestOwed); if (currentDepositValue >= owed) { // Locked value more than owed deposits, positive surplus isNegative = false; surplusAmount = currentDepositValue.sub(owed); } else { // Locked value less than owed deposits, negative surplus isNegative = true; surplusAmount = owed.sub(currentDepositValue); } } function depositIsFunded(uint256 id) public view returns (bool) { return (id <= latestFundedDepositID); } function depositsLength() external view returns (uint256) { return deposits.length; } function fundingListLength() external view returns (uint256) { return fundingList.length; } function getDeposit(uint256 depositID) external view returns (Deposit memory) { return deposits[depositID.sub(1)]; } function getFunding(uint256 fundingID) external view returns (Funding memory) { return fundingList[fundingID.sub(1)]; } function moneyMarketIncomeIndex() external returns (uint256) { return moneyMarket.incomeIndex(); } /** Param setters */ function setFeeModel(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); feeModel = IFeeModel(newValue); emit ESetParamAddress(msg.sender, "feeModel", newValue); } function setInterestModel(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); interestModel = IInterestModel(newValue); emit ESetParamAddress(msg.sender, "interestModel", newValue); } function setInterestOracle(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); interestOracle = IInterestOracle(newValue); require( interestOracle.moneyMarket() == address(moneyMarket), "DInterest: moneyMarket mismatch" ); emit ESetParamAddress(msg.sender, "interestOracle", newValue); } function setRewards(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); moneyMarket.setRewards(newValue); emit ESetParamAddress(msg.sender, "moneyMarket.rewards", newValue); } function setMPHMinter(address newValue) external onlyOwner { require(newValue.isContract(), "DInterest: not contract"); mphMinter = MPHMinter(newValue); emit ESetParamAddress(msg.sender, "mphMinter", newValue); } function setMinDepositPeriod(uint256 newValue) external onlyOwner { require(newValue <= MaxDepositPeriod, "DInterest: invalid value"); MinDepositPeriod = newValue; emit ESetParamUint(msg.sender, "MinDepositPeriod", newValue); } function setMaxDepositPeriod(uint256 newValue) external onlyOwner { require( newValue >= MinDepositPeriod && newValue > 0, "DInterest: invalid value" ); MaxDepositPeriod = newValue; emit ESetParamUint(msg.sender, "MaxDepositPeriod", newValue); } function setMinDepositAmount(uint256 newValue) external onlyOwner { require( newValue <= MaxDepositAmount && newValue > 0, "DInterest: invalid value" ); MinDepositAmount = newValue; emit ESetParamUint(msg.sender, "MinDepositAmount", newValue); } function setMaxDepositAmount(uint256 newValue) external onlyOwner { require( newValue >= MinDepositAmount && newValue > 0, "DInterest: invalid value" ); MaxDepositAmount = newValue; emit ESetParamUint(msg.sender, "MaxDepositAmount", newValue); } function setDepositNFTTokenURI(uint256 tokenId, string calldata newURI) external onlyOwner { depositNFT.setTokenURI(tokenId, newURI); } function setDepositNFTBaseURI(string calldata newURI) external onlyOwner { depositNFT.setBaseURI(newURI); } function setDepositNFTContractURI(string calldata newURI) external onlyOwner { depositNFT.setContractURI(newURI); } function setFundingNFTTokenURI(uint256 tokenId, string calldata newURI) external onlyOwner { fundingNFT.setTokenURI(tokenId, newURI); } function setFundingNFTBaseURI(string calldata newURI) external onlyOwner { fundingNFT.setBaseURI(newURI); } function setFundingNFTContractURI(string calldata newURI) external onlyOwner { fundingNFT.setContractURI(newURI); } /** Internal getters */ function _getDeposit(uint256 depositID) internal view returns (Deposit storage) { return deposits[depositID.sub(1)]; } function _getFunding(uint256 fundingID) internal view returns (Funding storage) { return fundingList[fundingID.sub(1)]; } /** Internals */ function _deposit(uint256 amount, uint256 maturationTimestamp) internal { // Ensure deposit amount is not more than maximum require( amount >= MinDepositAmount && amount <= MaxDepositAmount, "DInterest: Deposit amount out of range" ); // Ensure deposit period is at least MinDepositPeriod uint256 depositPeriod = maturationTimestamp.sub(now); require( depositPeriod >= MinDepositPeriod && depositPeriod <= MaxDepositPeriod, "DInterest: Deposit period out of range" ); // Update totalDeposit totalDeposit = totalDeposit.add(amount); // Calculate interest uint256 interestAmount = calculateInterestAmount(amount, depositPeriod); require(interestAmount > 0, "DInterest: interestAmount == 0"); // Update funding related data uint256 id = deposits.length.add(1); unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add( interestAmount ); // Update totalInterestOwed totalInterestOwed = totalInterestOwed.add(interestAmount); // Mint MPH for msg.sender uint256 mintMPHAmount = mphMinter.mintDepositorReward( msg.sender, amount, depositPeriod, interestAmount ); // Record deposit data for `msg.sender` deposits.push( Deposit({ amount: amount, maturationTimestamp: maturationTimestamp, interestOwed: interestAmount, initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(), active: true, finalSurplusIsNegative: false, finalSurplusAmount: 0, mintMPHAmount: mintMPHAmount, depositTimestamp: now }) ); // Transfer `amount` stablecoin to DInterest stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Lend `amount` stablecoin to money market stablecoin.safeIncreaseAllowance(address(moneyMarket), amount); moneyMarket.deposit(amount); // Mint depositNFT depositNFT.mint(msg.sender, id); // Emit event emit EDeposit( msg.sender, id, amount, maturationTimestamp, interestAmount, mintMPHAmount ); } function _withdraw( uint256 depositID, uint256 fundingID, bool early ) internal { Deposit storage depositEntry = _getDeposit(depositID); // Verify deposit is active and set to inactive require(depositEntry.active, "DInterest: Deposit not active"); depositEntry.active = false; if (early) { // Verify `now < depositEntry.maturationTimestamp` require( now < depositEntry.maturationTimestamp, "DInterest: Deposit mature, use withdraw() instead" ); // Verify `now > depositEntry.depositTimestamp` require( now > depositEntry.depositTimestamp, "DInterest: Deposited in same block" ); } else { // Verify `now >= depositEntry.maturationTimestamp` require( now >= depositEntry.maturationTimestamp, "DInterest: Deposit not mature" ); } // Verify msg.sender owns the depositNFT require( depositNFT.ownerOf(depositID) == msg.sender, "DInterest: Sender doesn't own depositNFT" ); // Restrict scope to prevent stack too deep error { // Take back MPH uint256 takeBackMPHAmount = mphMinter.takeBackDepositorReward( msg.sender, depositEntry.mintMPHAmount, early ); // Emit event emit EWithdraw( msg.sender, depositID, fundingID, early, takeBackMPHAmount ); } // Update totalDeposit totalDeposit = totalDeposit.sub(depositEntry.amount); // Update totalInterestOwed totalInterestOwed = totalInterestOwed.sub(depositEntry.interestOwed); // Fetch the income index & surplus before withdrawal, to prevent our withdrawal from // increasing the income index when the money market vault total supply is extremely small // (vault as in yEarn & Harvest vaults) uint256 currentMoneyMarketIncomeIndex = moneyMarket.incomeIndex(); require( currentMoneyMarketIncomeIndex > 0, "DInterest: currentMoneyMarketIncomeIndex == 0" ); (bool depositSurplusIsNegative, uint256 depositSurplus) = surplusOfDeposit(depositID); // Restrict scope to prevent stack too deep error { uint256 feeAmount; uint256 withdrawAmount; if (early) { // Withdraw the principal of the deposit from money market withdrawAmount = depositEntry.amount; } else { // Withdraw the principal & the interest from money market feeAmount = feeModel.getFee(depositEntry.interestOwed); withdrawAmount = depositEntry.amount.add( depositEntry.interestOwed ); } withdrawAmount = moneyMarket.withdraw(withdrawAmount); // Send `withdrawAmount - feeAmount` stablecoin to `msg.sender` stablecoin.safeTransfer(msg.sender, withdrawAmount.sub(feeAmount)); // Send `feeAmount` stablecoin to feeModel beneficiary if (feeAmount > 0) { stablecoin.safeTransfer(feeModel.beneficiary(), feeAmount); } } // If deposit was funded, payout interest to funder if (depositIsFunded(depositID)) { _payInterestToFunder( fundingID, depositID, depositEntry.amount, depositEntry.maturationTimestamp, depositEntry.interestOwed, depositSurplusIsNegative, depositSurplus, currentMoneyMarketIncomeIndex, early ); } else { // Remove deposit from future deficit fundings unfundedUserDepositAmount = unfundedUserDepositAmount.sub( depositEntry.amount.add(depositEntry.interestOwed) ); // Record remaining surplus if (!early) { depositEntry.finalSurplusIsNegative = depositSurplusIsNegative; depositEntry.finalSurplusAmount = depositSurplus; } } } function _payInterestToFunder( uint256 fundingID, uint256 depositID, uint256 depositAmount, uint256 depositMaturationTimestamp, uint256 depositInterestOwed, bool depositSurplusIsNegative, uint256 depositSurplus, uint256 currentMoneyMarketIncomeIndex, bool early ) internal { Funding storage f = _getFunding(fundingID); require( depositID > f.fromDepositID && depositID <= f.toDepositID, "DInterest: Deposit not funded by fundingID" ); uint256 interestAmount = f .recordedFundedDepositAmount .mul(currentMoneyMarketIncomeIndex) .div(f.recordedMoneyMarketIncomeIndex) .sub(f.recordedFundedDepositAmount); // Update funding values sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex .sub( f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div( f.recordedMoneyMarketIncomeIndex ) ); f.recordedFundedDepositAmount = f.recordedFundedDepositAmount.sub( depositAmount.add(depositInterestOwed) ); f.recordedMoneyMarketIncomeIndex = currentMoneyMarketIncomeIndex; sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex = sumOfRecordedFundedDepositAndInterestAmountDivRecordedIncomeIndex .add( f.recordedFundedDepositAmount.mul(EXTRA_PRECISION).div( f.recordedMoneyMarketIncomeIndex ) ); // Send interest to funder address funder = fundingNFT.ownerOf(fundingID); uint256 transferToFunderAmount = (early && depositSurplusIsNegative) ? interestAmount.add(depositSurplus) : interestAmount; if (transferToFunderAmount > 0) { transferToFunderAmount = moneyMarket.withdraw( transferToFunderAmount ); if (transferToFunderAmount > 0) { stablecoin.safeTransfer(funder, transferToFunderAmount); } } // Mint funder rewards mphMinter.mintFunderReward( funder, depositAmount, f.creationTimestamp, depositMaturationTimestamp, interestAmount, early ); } function _fund(uint256 totalDeficit) internal { // Transfer `totalDeficit` stablecoins from msg.sender stablecoin.safeTransferFrom(msg.sender, address(this), totalDeficit); // Deposit `totalDeficit` stablecoins into moneyMarket stablecoin.safeIncreaseAllowance(address(moneyMarket), totalDeficit); moneyMarket.deposit(totalDeficit); // Mint fundingNFT fundingNFT.mint(msg.sender, fundingList.length); // Emit event uint256 fundingID = fundingList.length; emit EFund(msg.sender, fundingID, totalDeficit); } }
Ensure deposit amount is not more than maximum Ensure deposit period is at least MinDepositPeriod Update totalDeposit Calculate interest Update funding related data Update totalInterestOwed Mint MPH for msg.sender Record deposit data for `msg.sender`
function _deposit(uint256 amount, uint256 maturationTimestamp) internal { require( amount >= MinDepositAmount && amount <= MaxDepositAmount, "DInterest: Deposit amount out of range" ); uint256 depositPeriod = maturationTimestamp.sub(now); require( depositPeriod >= MinDepositPeriod && depositPeriod <= MaxDepositPeriod, "DInterest: Deposit period out of range" ); totalDeposit = totalDeposit.add(amount); uint256 interestAmount = calculateInterestAmount(amount, depositPeriod); require(interestAmount > 0, "DInterest: interestAmount == 0"); uint256 id = deposits.length.add(1); unfundedUserDepositAmount = unfundedUserDepositAmount.add(amount).add( interestAmount ); totalInterestOwed = totalInterestOwed.add(interestAmount); uint256 mintMPHAmount = mphMinter.mintDepositorReward( msg.sender, amount, depositPeriod, interestAmount ); deposits.push( Deposit({ amount: amount, maturationTimestamp: maturationTimestamp, interestOwed: interestAmount, initialMoneyMarketIncomeIndex: moneyMarket.incomeIndex(), active: true, finalSurplusIsNegative: false, finalSurplusAmount: 0, mintMPHAmount: mintMPHAmount, depositTimestamp: now }) ); moneyMarket.deposit(amount); msg.sender, id, amount, maturationTimestamp, interestAmount, mintMPHAmount ); }
892,260
./partial_match/1/0x66bB9D104c55861feb3Ec3559433F01f6373c966/sources/contracts/FXPool.sol
get asset arrangement of the token in the vault
function _getAssetIndex(address _assetAddress) internal view returns (uint256) { require(_assetAddress == derivatives[0] || _assetAddress == derivatives[1], 'FXPool/address-not-a-derivative'); if (_assetAddress == derivatives[0]) { return 0; return 1; } }
15,919,443
pragma solidity 0.5.8; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract FlightSuretyData is Ownable { using SafeMath for uint256; // Blocks all state changes throughout the contract if false bool private operational = true; // Contracts that are allowed to call functions in this contract mapping(address => bool) private authorizedContracts; // Tracks number of authorizedContracts uint256 private numAuthorizedContracts = 0; mapping(address => bool) private airlines; uint256 private numAirlines = 0; mapping(address => uint256) private funding; struct Flight { uint8 status; address airline; string flight; uint256 timestamp; address[] insurees; mapping(address => uint256) insuredAmounts; bool isProcessed; } mapping(bytes32 => Flight) private flights; mapping(address => uint256) private credits; event OperationStatusSet(bool status); // Contract authorization events event ContractAuthorized(address authorizedContract); event ContractDeauthorized(address deauthorizedContract); // Contract funding event event Funded(address fundedBy, uint256 fundingAmount); // Airline registration events event AirlineRegistered(address airline); event AirlineDeregistered(address airline); event FlightRegistered( bytes32 flightKey, address airline, string flight, uint256 timestamp ); // Insurance events event InsuranceBought( address airline, string flight, uint256 timestamp, address insuree, uint256 insuredAmount ); event InsureesCredited( address airline, string flight, uint256 timestamp, uint256 totalPayout ); /** * @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, "Data contract is currently not operational"); _; } /** * @dev Modifier that requires the caller to be an authorized contract * or the contract owner in case there are no authorized contracts. * This effectively gives the ownership of this contract back to the * authorized calling contract instead of the contract creator. */ modifier requireAuthorization() { if(numAuthorizedContracts > 0) { require(authorizedContracts[msg.sender], "Caller is not an authorized contract"); } else { require(owner() == tx.origin, "Caller is not contract owner"); } _; } /** * @dev Modifier that requires the caller to explicitly be an authorized contract */ modifier requireAuthorizedContract() { require(authorizedContracts[msg.sender], "Caller is not an authorized contract"); _; } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } /** * @dev Whitelists a contract so that it may call this contract */ function authorizeContract(address authorizedContract) external requireAuthorization { authorizedContracts[authorizedContract] = true; numAuthorizedContracts = numAuthorizedContracts.add(1); emit ContractAuthorized(authorizedContract); } /** * @dev Delist an authorized contract so that it can't call this contract */ function deauthorizeContract(address deauthorizedContract) external requireAuthorization { numAuthorizedContracts = numAuthorizedContracts.sub(1); delete authorizedContracts[deauthorizedContract]; emit ContractDeauthorized(deauthorizedContract); } /** * @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 requireAuthorization { operational = mode; emit OperationStatusSet(mode); } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline) external requireIsOperational requireAuthorization { if(!airlines[airline]) { airlines[airline] = true; numAirlines = numAirlines.add(1); emit AirlineRegistered(airline); } } /** * @dev Remove an airline from the registration queue * Can only be called from FlightSuretyApp contract * */ function deregisterAirline(address airline) external requireIsOperational requireAuthorization { if(airlines[airline]) { delete airlines[airline]; numAirlines = numAirlines.sub(1); emit AirlineDeregistered(airline); } } /** * @dev Register a future flight for insuring */ function registerFlight( address airline, string calldata flight, uint256 timestamp ) external requireAuthorizedContract requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); Flight memory f; f.airline = airline; f.flight = flight; f.timestamp = timestamp; f.isProcessed = false; flights[flightKey] = f; emit FlightRegistered(flightKey, airline, flight, timestamp); } /** * @dev Buy insurance for a flight */ function buyInsurance( address airline, string calldata flight, uint256 timestamp ) external payable requireAuthorizedContract requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); // Prevent buying against invalid flight keys require(flights[flightKey].timestamp > 0, "Flight not registered"); // Prevent double purchase attempts require( flights[flightKey].insuredAmounts[tx.origin] == 0, "Cannot buy more than once" ); flights[flightKey].insurees.push(tx.origin); flights[flightKey].insuredAmounts[tx.origin] = msg.value; emit InsuranceBought(airline, flight, timestamp, tx.origin, msg.value); } /** * @dev Credits payouts to insurees */ function creditInsurees(bytes32 flightKey, uint256 numerator, uint256 denominator) external requireAuthorizedContract requireIsOperational { uint256 totalPayout = 0; address insuree; uint256 payout = 0; for(uint256 i=0; i < flights[flightKey].insurees.length; i++) { insuree = flights[flightKey].insurees[i]; payout = flights[flightKey].insuredAmounts[insuree]; payout = payout * numerator / denominator; credits[insuree] = credits[insuree].add(payout); totalPayout = totalPayout.add(payout); } emit InsureesCredited( flights[flightKey].airline, flights[flightKey].flight, flights[flightKey].timestamp, totalPayout ); } /** * @dev Marks given flight as processed */ function markFlightAsProcessed(bytes32 flightKey, uint8 statusCode) external requireAuthorizedContract requireIsOperational { flights[flightKey].isProcessed = true; flights[flightKey].status = statusCode; } /** * @dev Transfers eligible payout funds to insuree */ function payInsuree(address payable insuree, uint256 amount) external requireAuthorizedContract requireIsOperational { require(amount <= credits[insuree], "Insufficient credits balance"); credits[insuree] = credits[insuree].sub(amount); insuree.transfer(amount); } /** * @dev Get operating status of contract */ function isOperational() public view returns(bool) { return operational; } /** * @dev Get authorization status of contract */ function isAuthorizedContract(address contractAddr) public view returns(bool) { return authorizedContracts[contractAddr]; } /** * @dev Get registration status of an airline */ function isRegisteredAirline(address airline) external view returns(bool) { return airlines[airline]; } /** * @dev Get number of registered airlines */ function getNumRegisteredAirlines() external view returns(uint256) { return numAirlines; } /** * @dev Get amount of funding done by an airline */ function getAirlineFundingContribution(address airline) external view returns(uint256) { return funding[airline]; } /** * @dev Returns false if flight is registered and is not processed, else returns true */ function isFlightProcessed(bytes32 flightKey) external view returns(bool) { return !(flights[flightKey].timestamp != 0 && !flights[flightKey].isProcessed); } /** * @dev Returns flight delay status */ function getFlightStatus(address airline, string calldata flight, uint256 timestamp) external view returns(uint8) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return flights[flightKey].status; } /** * @dev Returns insuree credits balance from payouts */ function getFundsBalance() external view returns(uint256) { return credits[msg.sender]; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * Should be directly made to the dataContract */ function fund() public payable { uint256 amount = msg.value; funding[msg.sender] = funding[msg.sender].add(amount); emit Funded(msg.sender, amount); } function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } }
Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining Should be directly made to the dataContract/
function fund() public payable { uint256 amount = msg.value; funding[msg.sender] = funding[msg.sender].add(amount); emit Funded(msg.sender, amount); }
12,832,456
//SPDX-License-Identifier: MIT pragma solidity 0.8.10; /* Library Imports */ import { Lib_SecureMerkleTrie } from "./trie/Lib_SecureMerkleTrie.sol"; import { Lib_CrossDomainUtils } from "./Lib_CrossDomainUtils.sol"; /** * @title WithdrawalVerifier * @notice A library with helper functions for verifying a withdrawal on L1. */ library WithdrawalVerifier { /// @notice A struct containing the elements hashed together to generate the output root. struct OutputRootProof { bytes32 version; bytes32 stateRoot; bytes32 withdrawerStorageRoot; bytes32 latestBlockhash; } /** * @notice Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract * @param _nonce Nonce for the provided message. * @param _sender Message sender address on L2. * @param _target Target address on L1. * @param _value ETH to send to the target. * @param _gasLimit Gas to be forwarded to the target. * @param _data Data to send to the target. */ function withdrawalHash( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal pure returns (bytes32) { return keccak256(abi.encode(_nonce, _sender, _target, _value, _gasLimit, _data)); } /** * @notice Derives the output root corresponding to the elements provided in the proof. * @param _outputRootProof The elements which were hashed together to generate the output root. * @return Whether or not the output root matches the hashed output of the proof. */ function _deriveOutputRoot(OutputRootProof memory _outputRootProof) internal pure returns (bytes32) { return keccak256( abi.encode( _outputRootProof.version, _outputRootProof.stateRoot, _outputRootProof.withdrawerStorageRoot, _outputRootProof.latestBlockhash ) ); } /** * @notice Verifies a proof that a given withdrawal hash is present in the Withdrawer contract's * withdrawals mapping. * @param _withdrawalHash Keccak256 hash of the withdrawal transaction data. * @param _withdrawerStorageRoot Storage root of the withdrawer predeploy contract. * @param _withdrawalProof Merkle trie inclusion proof for the desired node. * @return Whether or not the inclusion proof was successful. */ function _verifyWithdrawalInclusion( bytes32 _withdrawalHash, bytes32 _withdrawerStorageRoot, bytes memory _withdrawalProof ) internal pure returns (bool) { bytes32 storageKey = keccak256( abi.encode( _withdrawalHash, uint256(0) // The withdrawals mapping is at the first slot in the layout. ) ); return Lib_SecureMerkleTrie.verifyInclusionProof( abi.encode(storageKey), hex"01", _withdrawalProof, _withdrawerStorageRoot ); } }
Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract _nonce Nonce for the provided message. _sender Message sender address on L2. _target Target address on L1. _value ETH to send to the target. _gasLimit Gas to be forwarded to the target. _data Data to send to the target./
function withdrawalHash( uint256 _nonce, address _sender, address _target, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal pure returns (bytes32) { return keccak256(abi.encode(_nonce, _sender, _target, _value, _gasLimit, _data)); }
13,110,098
./partial_match/42/0x5fd9A1cA8fbbf50D1832F425DC262f263a5FE2F1/sources/FluxAggregator.sol
Allows an ownership transfer to be completed by the recipient./
function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); }
8,935,853
pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../lib/SignerRecover.sol"; import "../interfaces/IBurn.sol"; import "../lib/Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "../interfaces/IMint.sol"; contract LetsFarm is Upgradeable, SignerRecover, IERC721ReceiverUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; IERC20Upgradeable public hpl; IERC20Upgradeable public hpw; address public operator; struct UserInfo { uint256 hplDeposit; uint256 hpwDeposit; uint256 lastUpdatedAt; uint256 hplRewardClaimed; uint256 hpwRewardClaimed; uint256 lastRewardClaimedAt; } struct DepositedNFT { uint256[] depositedTokenIds; mapping(uint256 => uint256) tokenIdToIndex; //index + 1 } mapping(address => UserInfo) public userInfo; //nft => user => DepositedNFT mapping(address => mapping(address => DepositedNFT)) nftUserInfo; //events event TokenDeposit(address depositor, uint256 hplAmount, uint256 hpwAmount); event TokenWithdraw( address withdrawer, uint256 hplAmount, uint256 hpwAmount ); event NFTDeposit(address nft, address depositor, bytes tokenIds); event NFTWithdraw(address nft, address withdrawer, bytes tokenIds); event RewardsClaimed(address claimer, uint256 hplAmount, uint256 hpwAmount); struct UserInfoTokenWithdraw { uint256 hplWithdraw; uint256 hpwWithdraw; } mapping(address => UserInfoTokenWithdraw) public userInfoTokenWithdraw; uint256 public minTimeBetweenClaims; uint256 public contractStartAt; function initialize( IERC20Upgradeable _hpl, IERC20Upgradeable _hpw, address _operator ) external initializer { initOwner(); minTimeBetweenClaims = 10 days; contractStartAt = block.timestamp; hpl = _hpl; hpw = _hpw; operator = _operator; } function setMinTimeBetweenClaims(uint256 _minTimeBetweenClaims) external onlyOwner { minTimeBetweenClaims = _minTimeBetweenClaims; } function setContractStart() external onlyOwner { contractStartAt = block.timestamp; } function setContractStartWithTime(uint256 _time) external onlyOwner { contractStartAt = _time; } function setOperator(address _op) external onlyOwner { operator = _op; } function depositTokensToPlay(uint256 _hplAmount, uint256 _hpwAmount) external { hpl.safeTransferFrom(msg.sender, address(this), _hplAmount); hpw.safeTransferFrom(msg.sender, address(this), _hpwAmount); userInfo[msg.sender].hplDeposit += _hplAmount; userInfo[msg.sender].hpwDeposit += _hpwAmount; userInfo[msg.sender].lastUpdatedAt = block.timestamp; emit TokenDeposit(msg.sender, _hplAmount, _hpwAmount); } function depositNFTsToPlay(address _nft, uint256[] memory _tokenIds) external { DepositedNFT storage _user = nftUserInfo[_nft][msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { IERC721Upgradeable(_nft).transferFrom( msg.sender, address(this), _tokenIds[i] ); _user.depositedTokenIds.push(_tokenIds[i]); _user.tokenIdToIndex[_tokenIds[i]] = _user.depositedTokenIds.length; } userInfo[msg.sender].lastUpdatedAt = block.timestamp; emit NFTDeposit(_nft, msg.sender, abi.encodePacked(_tokenIds)); } function withdrawNFTs( address _nft, uint256[] memory _tokenIds, uint256 _expiredTime, bytes32 r, bytes32 s, uint8 v ) external { require(block.timestamp < _expiredTime, "withdrawNFTs: !expired"); bytes32 msgHash = keccak256( abi.encode(_nft, msg.sender, _tokenIds, _expiredTime) ); require( operator == recoverSigner(r, s, v, msgHash), "invalid operator" ); DepositedNFT storage _user = nftUserInfo[_nft][msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { require(_user.tokenIdToIndex[_tokenIds[i]] > 0, "invalid tokenId"); IERC721Upgradeable(_nft).transferFrom( address(this), msg.sender, _tokenIds[i] ); //swap uint256 _index = _user.tokenIdToIndex[_tokenIds[i]] - 1; _user.depositedTokenIds[_index] = _user.depositedTokenIds[ _user.depositedTokenIds.length - 1 ]; _user.tokenIdToIndex[_user.depositedTokenIds[_index]] = _index + 1; _user.depositedTokenIds.pop(); delete _user.tokenIdToIndex[_tokenIds[i]]; } userInfo[msg.sender].lastUpdatedAt = block.timestamp; emit NFTWithdraw(_nft, msg.sender, abi.encodePacked(_tokenIds)); } function withdrawTokens( uint256 _hplSpent, uint256 _hplWithdrawAmount, uint256 _hpwSpent, uint256 _hpwWithdrawAmount, uint256 _expiredTime, bytes32 r, bytes32 s, uint8 v ) external { require(block.timestamp < _expiredTime, "withdrawTokens: !expired"); bytes32 msgHash = keccak256( abi.encode( msg.sender, _hplSpent, _hplWithdrawAmount, _hpwSpent, _hpwWithdrawAmount, _expiredTime ) ); require( operator == recoverSigner(r, s, v, msgHash), "invalid operator" ); UserInfo storage _user = userInfo[msg.sender]; UserInfoTokenWithdraw storage _userInfoTokenWithdraw = userInfoTokenWithdraw[msg.sender]; require( _user.hplDeposit >= _hplSpent + _hplWithdrawAmount + _userInfoTokenWithdraw.hplWithdraw, "invalid hplSpent" ); require( _user.hpwDeposit >= _hpwSpent + _hpwWithdrawAmount + _userInfoTokenWithdraw.hpwWithdraw, "invalid hpwSpent" ); //return hpl hpl.safeTransfer(msg.sender, _hplWithdrawAmount); //return hpw hpw.safeTransfer(msg.sender, _hpwWithdrawAmount); //burn hplSpent and hpwSpent // IBurn(address(hpl)).burn(_hplSpent); // IBurn(address(hpw)).burn(_hpwSpent); emit TokenWithdraw(msg.sender, _hplWithdrawAmount, _hpwWithdrawAmount); _userInfoTokenWithdraw.hplWithdraw += _hplWithdrawAmount; _userInfoTokenWithdraw.hpwWithdraw += _hpwWithdrawAmount; _user.lastUpdatedAt = block.timestamp; } function claimRewards( uint256 _hplRewards, uint256 _hpwRewards, uint256 _expiredTime, bytes32 r, bytes32 s, uint8 v ) external { require(block.timestamp < _expiredTime, "claimRewards: !expired"); bytes32 msgHash = keccak256( abi.encode(msg.sender, _hplRewards, _hpwRewards, _expiredTime) ); require( operator == recoverSigner(r, s, v, msgHash), "invalid operator" ); UserInfo storage _user = userInfo[msg.sender]; uint256 _lastRewardClaimedAt = _user.lastRewardClaimedAt > 0 ? _user.lastRewardClaimedAt : contractStartAt; require( _lastRewardClaimedAt + minTimeBetweenClaims < block.timestamp, "!minTimeBetweenClaims" ); require(_user.hplRewardClaimed <= _hplRewards, "invalid _hplRewards"); require(_user.hpwRewardClaimed <= _hpwRewards, "invalid _hpwRewards"); uint256 toTransferHpl = _hplRewards - _user.hplRewardClaimed; uint256 toTransferHpw = _hpwRewards - _user.hpwRewardClaimed; address _land = 0x9c271b95A2Aa7Ab600b9B2E178CbBec2A6dc1bAb; uint256 depositedLandCount = getLandDepositedCount(msg.sender, _land); uint256 maxWithdrawal = 3000e18 * depositedLandCount; if (toTransferHpw > maxWithdrawal) { toTransferHpw = maxWithdrawal; if (toTransferHpw > 10000e18) { toTransferHpw = 10000e18; } _hpwRewards = _user.hpwRewardClaimed + toTransferHpw; } _user.hplRewardClaimed = _hplRewards; _user.hpwRewardClaimed = _hpwRewards; _user.lastRewardClaimedAt = block.timestamp; hpl.safeTransfer(msg.sender, toTransferHpl); //mint hpw rewards IMint(address(hpw)).mint(msg.sender, toTransferHpw); emit RewardsClaimed(msg.sender, toTransferHpl, toTransferHpw); } function getUserInfo(address _user) external view returns ( uint256 hplDeposit, uint256 hpwDeposit, uint256 lastUpdatedAt, uint256 hplRewardClaimed, uint256 hpwRewardClaimed ) { UserInfo storage _userInfo = userInfo[_user]; return ( _userInfo.hplDeposit, _userInfo.hpwDeposit, _userInfo.lastUpdatedAt, _userInfo.hplRewardClaimed, _userInfo.hpwRewardClaimed ); } function getUserInfo2(address _user) external view returns ( uint256 hplDeposit, uint256 hpwDeposit, uint256 lastUpdatedAt, uint256 hplRewardClaimed, uint256 hpwRewardClaimed, uint256 lastRewardClaimedAt ) { UserInfo storage _userInfo = userInfo[_user]; return ( _userInfo.hplDeposit, _userInfo.hpwDeposit, _userInfo.lastUpdatedAt, _userInfo.hplRewardClaimed, _userInfo.hpwRewardClaimed, _userInfo.lastRewardClaimedAt ); } function getDepositedNFTs(address _nft, address _user) external view returns (uint256[] memory depositedLands) { return nftUserInfo[_nft][_user].depositedTokenIds; } function getDepositedNFTs2(address _nft, address _user) external view returns (uint256[] memory depositedLands) { return nftUserInfo[_nft][_user].depositedTokenIds; } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { //do nothing return bytes4(""); } function getLandDepositedCount(address _addr, address _nft) public view returns (uint256) { return nftUserInfo[_nft][_addr].depositedTokenIds.length; } }
return hplreturn hpwburn hplSpent and hpwSpent IBurn(address(hpl)).burn(_hplSpent); IBurn(address(hpw)).burn(_hpwSpent);
function withdrawTokens( uint256 _hplSpent, uint256 _hplWithdrawAmount, uint256 _hpwSpent, uint256 _hpwWithdrawAmount, uint256 _expiredTime, bytes32 r, bytes32 s, uint8 v ) external { require(block.timestamp < _expiredTime, "withdrawTokens: !expired"); bytes32 msgHash = keccak256( abi.encode( msg.sender, _hplSpent, _hplWithdrawAmount, _hpwSpent, _hpwWithdrawAmount, _expiredTime ) ); require( operator == recoverSigner(r, s, v, msgHash), "invalid operator" ); UserInfo storage _user = userInfo[msg.sender]; UserInfoTokenWithdraw storage _userInfoTokenWithdraw = userInfoTokenWithdraw[msg.sender]; require( _user.hplDeposit >= _hplSpent + _hplWithdrawAmount + _userInfoTokenWithdraw.hplWithdraw, "invalid hplSpent" ); require( _user.hpwDeposit >= _hpwSpent + _hpwWithdrawAmount + _userInfoTokenWithdraw.hpwWithdraw, "invalid hpwSpent" ); hpl.safeTransfer(msg.sender, _hplWithdrawAmount); hpw.safeTransfer(msg.sender, _hpwWithdrawAmount); emit TokenWithdraw(msg.sender, _hplWithdrawAmount, _hpwWithdrawAmount); _userInfoTokenWithdraw.hplWithdraw += _hplWithdrawAmount; _userInfoTokenWithdraw.hpwWithdraw += _hpwWithdrawAmount; _user.lastUpdatedAt = block.timestamp; }
13,042,021
./full_match/3/0x03b0258e8A3d9C0a7574bD55b06815998345ec1B/sources/contracts/DiamondHoldTestETH.sol
Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through {transferFrom}. This is zero by default./
function allowance(address owner, address account) public view override returns (uint256) { return _allowances[owner][account]; }
8,267,699
pragma solidity ^0.5.0; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC721/ERC721Full.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/drafts/Counters.sol"; /** ERC721 Token URI JSON Schema { "title": "Vehicle Metadata", "type": "object", "properties": { "make": { "type": "string", "description": "Ford" }, "model": { "type": "string", "description": "Fusion" }, "year": { "type": "uint", "description": "2014" } } } **/ contract CryptoFax is ERC721Full { constructor() ERC721Full("CryptoFax", "CARS") public { } using Counters for Counters.Counter; Counters.Counter token_ids; struct Car { string vin; uint accidents; } // Stores token_id => Car // Only permanent data that you would need to use within the smart contract later should be stored on-chain mapping(uint => Car) public cars; event Accident(uint token_id, string report_uri); function registerVehicle(address owner, string memory vin, string memory token_uri) public returns(uint) { token_ids.increment(); uint token_id = token_ids.current(); _mint(owner, token_id); _setTokenURI(token_id, token_uri); cars[token_id] = Car(vin, 0); return token_id; } function reportAccident(uint token_id, string memory report_uri) public returns(uint) { cars[token_id].accidents += 1; // Permanently associates the report_uri with the token_id on-chain via Events for a lower gas-cost than storing directly in the contract's storage. emit Accident(token_id, report_uri); return cars[token_id].accidents; } }
Permanently associates the report_uri with the token_id on-chain via Events for a lower gas-cost than storing directly in the contract's storage.
function reportAccident(uint token_id, string memory report_uri) public returns(uint) { cars[token_id].accidents += 1; emit Accident(token_id, report_uri); return cars[token_id].accidents; }
5,476,634
pragma solidity ^0.4.18; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol"; /* Eidoo ICO Engine interface This interface enables Eidoo wallet to query our ICO and display all the informations needed in the app */ contract ICOEngineInterface{ function started() public view returns(bool); function ended() public view returns(bool); function startTime() public view returns(uint); function endTime() public view returns(uint); function startBlock() public view returns(uint); function endBlock() public view returns(uint); function totalTokens() public view returns(uint); function remainingTokens() public view returns(uint); function price() public view returns(uint); } // ICO Abstract Contract contract ICOAC { function RC_TOKEN_LIMIT() public constant returns(uint); function getBlockNumberStart() constant public returns(uint); function getUacTokenBalance(address _of) constant public returns (uint); function buyTokensRC(address _buyer) payable public; function getTokensIcoSold() constant public returns (uint); } // UbiatarCoin Abstract Contract contract UACAC { function balanceOf(address _owner) public constant returns (uint256); } /* Reservation contract It will deliver an amount of tokens with a discount price a few hours before ICO begin */ contract ReservationContract is Ownable, ICOEngineInterface { // SafeMath standard lib using SafeMath for uint; // ICO contract address address public icoContractAddress = 0x0; // UbiatarCoin contract address address public uacTokenAddress = 0x0; // ICO block number start uint public icoBlockNumberStart = 0; // Reservation contract block number start uint public rcBlockNumberStart = 0; // ICO contract reference ICOAC public ico; // UbiatarCoint contract reference UACAC public uacToken; // Standard token price in USD CENTS per token uint public usdTokenPrice = 2 * 100; // The USD/ETH // UPDATE CHANGE RATE WITH CURRENT RATE WHEN DEPLOYING // This value is given in USD CENTS uint public usdPerEth = 1100 * 100; event LogReserve(address to, uint value); // Reservation contract constructor function ReservationContract() public {} /// modifiers // only during Reservation contract campaign modifier onlyInBlockNumberRange() { require(block.number >= rcBlockNumberStart); require(block.number < icoBlockNumberStart); _; } /// setters function setUsdTokenPrice(uint tokenPrice) public onlyOwner { usdTokenPrice = tokenPrice; } function setUsdPerEthRate(uint _usdPerEthRate) public onlyOwner { usdPerEth = _usdPerEthRate; } // set ICO contract address function setIcoContractAddress(address _icoContractAddress) public onlyOwner { icoContractAddress = _icoContractAddress; ico = ICOAC(_icoContractAddress); } // set UbiatarCoint ERC20 token contract address function setUacTokenAddress(address _uacTokenAddress) public onlyOwner { uacTokenAddress = _uacTokenAddress; uacToken = UACAC(_uacTokenAddress); } // set Reservation contract campaign block number start function setRCBlockNumberStart(uint _blockNumber) onlyOwner public { rcBlockNumberStart = _blockNumber; } /// functions // It gets ICO starting block number function getIcoBlockNumberStart() public onlyOwner { icoBlockNumberStart = ico.getBlockNumberStart(); } // It retrieves user reserved tokens function getReservedTokens(address investor) constant public returns (uint) { return uacToken.balanceOf(investor); } // Calculates the token price including the bonus percent received from the buyTokens function // Returns the amount of UAC per 1 ETH to be given function getUacTokensPerEth(uint bonusPercent) constant internal returns (uint) { uint tokenPrice = (usdTokenPrice.mul(100).mul(1 ether)).div(bonusPercent.add(100)); uint uacPerEth = (usdPerEth.mul(1 ether).mul(1 ether)).div(tokenPrice); return uacPerEth; } /// ICOEngineInterface // false if the ico is not started, true if the ico is started and running, true if the ico is completed function started() public view returns(bool) { return (rcBlockNumberStart != 0 && block.number >= rcBlockNumberStart && block.number < icoBlockNumberStart); } // false if the ico is not started, false if the ico is started and running, true if the ico is completed function ended() public view returns(bool) { return (icoBlockNumberStart != 0 && (block.number >= icoBlockNumberStart || ico.getTokensIcoSold() == ico.RC_TOKEN_LIMIT())); } // time stamp of the starting time of the ico, must return 0 if it depends on the block number function startTime() public view returns(uint) { return 0; } // time stamp of the ending time of the ico, must return 0 if it depends on the block number function endTime() public view returns(uint) { return 0; } // Optional function, can be implemented in place of startTime // Returns the starting block number of the ico, must return 0 if it depends on the time stamp function startBlock() public view returns(uint) { return rcBlockNumberStart; } // Optional function, can be implemented in place of endTime // Returns theending block number of the ico, must retrun 0 if it depends on the time stamp function endBlock() public view returns(uint) { return icoBlockNumberStart; } // returns the total number of the tokens available for the sale, must not change when the ico is started function totalTokens() public view returns(uint) { return ico.RC_TOKEN_LIMIT(); } // returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(), // then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens() function remainingTokens() public view returns(uint) { return ico.RC_TOKEN_LIMIT().sub(ico.getTokensIcoSold()); } // return the price as number of tokens released for each ether function price() public view returns(uint) { uint bonusPercent = 10; return getUacTokensPerEth(bonusPercent); } // Payback function to partecipate to Reservation contract campaign function() public payable onlyInBlockNumberRange { ico.buyTokensRC.value(msg.value)(msg.sender); LogReserve(msg.sender, msg.value); } }
returns the total number of the tokens available for the sale, must not change when the ico is started
function totalTokens() public view returns(uint) { return ico.RC_TOKEN_LIMIT(); }
15,804,950
./full_match/42/0xa9A0B3d480f6292B49FB09C4A9370D4b9267648A/sources/browser/MerkleDistributor.sol
Set merkle root for the next available window index and seed allocations. Callable by owner of this contract. Importantly, we assume that the owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur because we do not segregate reward balances by window, for code simplicity purposes.(If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must subsequently transfer in rewards or the following situation can occur). Example race situation: - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101). - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner correctly set `rewardsToDeposit` this time. - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = lastCreatedIndex; lastCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); }
16,280,349
pragma solidity 0.5.10; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @title DShops - Online Market Place Contract /// @author CHET S contract DShops is Pausable { using SafeMath for uint256; //////////////////////////////////////// State Variables & Mappings address private contractOwner; mapping(address => AdminStruct) private admins; address[] private adminIndexes; mapping(address => StoreOwnerApplicantStruct) private storeOwnerApplicants; address[] private storeOwnerApplicantIndexes; mapping(address => StoreOwnerStruct) private storeOwners; address[] private storeOwnerIndexes; mapping(bytes32 => storefrontStruct) private storefronts; // bytes32 represents uniqueId bytes32[] private storefrontIndexes; // bytes32[] stores a collection of uniqueIds mapping(bytes32 => ProductStruct) private products; // bytes32 represents productCode bytes32[] private productIndexes; // bytes32[] stores a collection of productCodes //////////////////////////////////////// Enums enum StoreOwnerApplicantStatus {None, Applied, Approved} //////////////////////////////////////// Structs struct AdminStruct { uint256 index; } struct StoreOwnerApplicantStruct { StoreOwnerApplicantStatus status; string name; uint256 index; } struct StoreOwnerStruct { bytes32[] storefrontUniqueIds; string name; uint256 index; } struct storefrontStruct { string storefrontName; address payable storeOwner; uint256 balance; mapping(bytes32 => uint256) productCodeIndexes; bytes32[] productCodes; uint256 index; } struct ProductStruct { bytes32 storefrontUniqueId; string name; uint256 price; uint256 availQty; uint256 index; string infoHash; string imageHash; } //////////////////////////////////////// Contructor /// @notice Assign msg.sender as the contractOwner as well as an Admin constructor() public { contractOwner = msg.sender; assignUserAsAdmin(msg.sender); } //////////////////////////////////////// Modifiers modifier onlyAdmin() { if (adminIndexes.length > 0) { require(isAdmin(msg.sender), "msg.sender must be an admin!"); } else { require(contractOwner == msg.sender, "msg.sender must at least the contract owner!"); } _; } modifier onlyStoreOwner() { require(isStoreOwner(msg.sender), "msg.sender must be a store owner!"); _; } modifier onlyStoreOwnerOfProduct(bytes32 productCode) { require(productExists(productCode), "product does not exist!"); require( msg.sender == storefronts[products[productCode].storefrontUniqueId].storeOwner, "msg.sender must be the store owner of the product!" ); _; } modifier onlyStoreOwnerOfStorefront(bytes32 storefrontUniqueId) { require(storefrontExists(storefrontUniqueId), "storefront does not exist!"); require( storefronts[storefrontUniqueId].storeOwner == msg.sender, "msg.sender must be the store owner of the storefront!" ); _; } //////////////////////////////////////// Events event LogAssignUserAsAdmin(address indexed adminAddr); event LogRequestToBeStoreOwner(address indexed storeOwnerApplicantAddr); event LogApproveStoreOwner(address indexed storeOwnerAddr); event LogCreateStorefront(bytes32 indexed storefrontUniqueId); event LogCreateProduct(bytes32 indexed productCode); event LogDeleteProduct(bytes32 indexed productCode); event LogUpdateProduct(bytes32 indexed productCode); event LogBuyProduct(address indexed buyer, bytes32 indexed productCode); event LogWithdrawBalanceFromStorefront(bytes32 indexed storefrontUniqueId); //////////////////////////////////////// Functions /// @notice Check if a user is an Admin or not /// @param userAddr The address of the user /// @return userIsAdmin as a boolean true or false function isAdmin(address userAddr) public view returns (bool userIsAdmin) { if (adminIndexes.length == 0) return false; return (adminIndexes[admins[userAddr].index] == userAddr); } /// @notice Assign a non-admin user as an Admin. Only an Admin can invoke this function /// and when the contract is not paused. /// @param userAddr The address to be assigned as an Admin /// @return index (uint256) of the added admin function assignUserAsAdmin(address userAddr) public whenNotPaused onlyAdmin returns (uint256 index) { require(!isAdmin(userAddr), "Operation aborted. User is already an Admin"); admins[userAddr].index = (adminIndexes.push(userAddr)).sub(1); emit LogAssignUserAsAdmin(userAddr); return (adminIndexes.length).sub(1); } /// @notice Get the total number of Admins /// @return count The total number of Admins in uint256 function getAdminsCount() public view returns (uint256 count) { return (adminIndexes.length); } /// @notice Get the address of an Admin by an index /// @param index The index of the Admin /// @return adminAddr The address of the Admin function getAdminByIndex(uint256 index) public view returns (address adminAddr) { require(adminIndexes.length > 0, "Operation aborted. No admins to retrieve"); adminAddr = adminIndexes[index]; return (adminAddr); } /// @notice Get the total number of Store Owner Applicants /// @return count The total number of Store Owner Applicants in uint256 function getStoreOwnerApplicantsCount() public view returns (uint256 count) { return (storeOwnerApplicantIndexes.length); } /// @notice Get the Store Owner Applicant by index /// @dev The storeOwnerApplicants contains data such as store owner name (name) /// and the application status (status). The storeOwnerApplicantIndexes is /// an array containing the store owner applicant addresses /// @param index The index of the store owner applicant /// @return userIsAdmin as a boolean true or false function getStoreOwnerApplicantByIndex(uint256 index) public view returns ( address storeOwnerApplicantAddr, string memory storeOwnerApplicantName, StoreOwnerApplicantStatus status ) { require( storeOwnerApplicantIndexes.length > 0, "Operation aborted. No store owner applicant to retrieve" ); /// Get the address of the store owner using the index /// and then use the address as the key to access the /// store owner applicant details such as name and status storeOwnerApplicantAddr = storeOwnerApplicantIndexes[index]; return ( storeOwnerApplicantAddr, storeOwnerApplicants[storeOwnerApplicantAddr].name, storeOwnerApplicants[storeOwnerApplicantAddr].status ); } /// @notice Check if a user is a store owner applicant /// @param userAddr The address of the user /// @return userIsStoreOwnerApplicant The boolean result function isStoreOwnerApplicant(address userAddr) public view returns (bool userIsStoreOwnerApplicant) { if (storeOwnerApplicantIndexes.length == 0) return false; return (storeOwnerApplicantIndexes[storeOwnerApplicants[userAddr].index] == userAddr); } /// @notice Make a user become a store owner applicant. Any user can make this request. /// @dev Only the first time applicant can be made an applicant. OpenZeppelin SafeMath is used /// @param applicantAddr The address of the store owner applicant /// @return index of the added store owner applicant in uint256 function requestToBeStoreOwner(address applicantAddr, string memory applicantName) public whenNotPaused returns (uint256 index) { require( !isStoreOwnerApplicant(applicantAddr), "Request ignored. The user is already an Applicant" ); /// Update initialize the status with 'Applied' and assign applicant name storeOwnerApplicants[applicantAddr].status = StoreOwnerApplicantStatus.Applied; storeOwnerApplicants[applicantAddr].name = applicantName; /// storeOnerApplicantIndexes.push would return the updated length of the array, /// subtract it by 1 would be the index of this newly added applicant /// OpenZeppelin SafeMath is used .sub(1) storeOwnerApplicants[applicantAddr].index = (storeOwnerApplicantIndexes.push(applicantAddr)) .sub(1); emit LogRequestToBeStoreOwner(applicantAddr); return (storeOwnerApplicantIndexes.length).sub(1); } /// @notice Add store owner applicant into the list of approved store owners. /// Only Admin is allow to invoke this function /// @param applicantAddr The address of the store owner applicant /// @return index The uint256 index of the approved store owner indexes array function approveStoreOwner(address applicantAddr) public whenNotPaused onlyAdmin returns (uint256 index) { require(isStoreOwnerApplicant(applicantAddr), "User must be a store applicant first"); require( storeOwnerApplicants[applicantAddr].status == StoreOwnerApplicantStatus.Applied, "User must be in the status of applied" ); /// Update the store owner applicant's application status to 'Approved' storeOwnerApplicants[applicantAddr].status = StoreOwnerApplicantStatus.Approved; /// Add the new store owner into storeOwners using the applicantAddr as the key /// storeOwners maps to a struct which holds the storeOwner's information /// storeOwnerIndexes is an array containing the storeOwner addresses /// Adding a store owner involves updating both the storeOwners and storeOwnerIndexes storeOwners[applicantAddr].name = storeOwnerApplicants[applicantAddr].name; storeOwners[applicantAddr].index = (storeOwnerIndexes.push(applicantAddr)).sub(1); emit LogApproveStoreOwner(applicantAddr); return (storeOwnerIndexes.length).sub(1); } /// @notice Check if a user is a store owner or not /// @param userAddr The address of the user /// @return userIsStoreOwner The boolean result function isStoreOwner(address userAddr) public view returns (bool userIsStoreOwner) { if (storeOwnerIndexes.length == 0) return false; return (storeOwnerIndexes[storeOwners[userAddr].index] == userAddr); } /// @notice Get the total number of store owners /// @return count The total number of store owners in uint256 function getStoreOwnersCount() public view returns (uint256 count) { return (storeOwnerIndexes.length); } /// @notice Get a store owner's data by Index /// @param index The index of the store owner /// @return storeOwnerAddr The address of the store owner /// @return storeOwnerName The store owner name /// @return storefrontsCount The total number of storefronts the store owner has function getStoreOwnerByIndex(uint256 index) public view returns (address storeOwnerAddr, string memory storeOwnerName, uint256 storefrontsCount) { require(storeOwnerIndexes.length > 0, "Operation aborted. No store owner to retrieve"); storeOwnerAddr = storeOwnerIndexes[index]; return ( storeOwnerAddr, storeOwners[storeOwnerAddr].name, storeOwners[storeOwnerAddr].storefrontUniqueIds.length ); } /// @notice Get a store owner's data by store owner's address /// @param addr The address of the store owner /// @return storeOwnerAddr The address of the store owner /// @return storeOwnerName The store owner name /// @return storefrontsCount The total number of storefronts the store owner has function getStoreOwner(address addr) public view returns (uint256 storeOwnerIndex, string memory storeOwnerName, uint256 storefrontsCount) { storeOwnerIndex = storeOwners[addr].index; storeOwnerName = storeOwners[addr].name; storefrontsCount = storeOwners[addr].storefrontUniqueIds.length; return (storeOwnerIndex, storeOwnerName, storefrontsCount); } /// @notice Create a storefront. Only a store owner can invoke this function. /// @dev A unique storefront identity would be generated based on the storefront name, /// a hash of the storefront name would be generated. /// Each store owner can own multiple storefronts, represented by an array of /// storefront unique IDs (hashes) /// @param newStorefrontName The name of the storefront to be created. /// @return index The index of the newly added storefront function createStorefront(string memory newStorefrontName) public whenNotPaused onlyStoreOwner returns (uint256 index) { /// Generate the hash to be used as the storefront unique ID bytes32 uniqueId = keccak256(abi.encodePacked(newStorefrontName)); require( !storefrontExists(uniqueId), "storefront name or storefront uniqueId already exists!" ); /// The msg.sender should be the store owner. /// Add the newly generated hash or storefront unique Id into /// the storefrontUniqueIds array storeOwners[msg.sender].storefrontUniqueIds.push(uniqueId); /// Populate the store owner's storefront record with the details /// Both storefronts (mapping to storefront struct) and /// storefrontIndexes (array of hashes) would be updated accordingly storefronts[uniqueId].storeOwner = msg.sender; storefronts[uniqueId].index = (storefrontIndexes.push(uniqueId)).sub(1); storefronts[uniqueId].storefrontName = newStorefrontName; storefronts[uniqueId].balance = 0; emit LogCreateStorefront(uniqueId); return (storefrontIndexes.length).sub(1); } /// @notice Get the total number of storefronts of all store owners /// @return count The total number of storefronts of all store owners in uint256 function getStorefrontsCount() public view returns (uint256 count) { return storefrontIndexes.length; } /// @notice Get the total number of storefronts of a particular store owner. /// Must provide a valid store owner's address /// @param storeOwnerAddr The storeowner's address /// @return count The total number of storefronts of a store store owner in uint256 function getStorefrontsCountForStoreOwner(address storeOwnerAddr) public view returns (uint256 count) { require(isStoreOwner(storeOwnerAddr), "Input address must be a store owner address"); return storeOwners[storeOwnerAddr].storefrontUniqueIds.length; } /// @notice Get the data of a storeowner's storefront by the storefront index /// @dev Get the data from the storefrontUniqueIds array based on index, /// where the storefrontUniqueIds belongs to a store owner identified by /// the storeOwnerAddr /// @param storeOwnerAddr The address of the store owner /// @param index The index (unint256) for fetching the storefront hash in the /// storefrontUniqueIds array /// @return storefrontName The name of the store owner's storefront indexed by index /// @return storefrontUniqueId The storefront unique id or hash /// @return productsCount The total number of products that the storefront has /// @return balance The balance in uint256 (wei) that the storefront has. /// The true balance will only be revealed to the storeowner who invokes this function. /// Non store owner to this storefront will only see zero for the balance. function getStorefrontForStoreOwnerByIndex(address storeOwnerAddr, uint256 index) public view returns ( string memory storefrontName, bytes32 storefrontUniqueId, uint256 productsCount, uint256 balance ) { /// Only the store owner who owns this storefront will get to see the actual balance, /// others would see a zero balance if (msg.sender == storeOwnerAddr) balance = storefronts[storeOwners[storeOwnerAddr].storefrontUniqueIds[index]].balance; else balance = 0; return ( storefronts[storeOwners[storeOwnerAddr].storefrontUniqueIds[index]].storefrontName, storeOwners[storeOwnerAddr].storefrontUniqueIds[index], storefronts[storeOwners[storeOwnerAddr].storefrontUniqueIds[index]].productCodes.length, balance ); } /// @notice Get a storefront by index, irrespective of store owner /// @dev Get the storefront by using the index to access the storefrontIndexes array /// @param index The index of the storefront, represented in storefrontIndexes /// @return uniqueId The unique storefront Id or hash /// @return storefrontName The storefront name /// @return storeOwner The store owner's address that owns this storefront /// @return productCodes The array of bytes32 representing the product codes that /// this storefront owns function getStorefrontByIndex(uint256 index) public view returns ( bytes32 uniqueId, string memory storefrontName, address storeOwner, uint256 productsCount, bytes32[] memory productCodes ) { uniqueId = storefrontIndexes[index]; productCodes = storefronts[uniqueId].productCodes; return ( uniqueId, storefronts[uniqueId].storefrontName, storefronts[uniqueId].storeOwner, storefronts[uniqueId].productCodes.length, productCodes ); } /// @notice Get as storefront by its storefront unique id or hash /// @param storefrontUniqueId The storefront unique id or hash /// @return storefrontName The storefront name /// @return storeOwner The storeowner's address who owns this storefront /// @return productsCount The total number of products that the storefront has /// @return balance The balance in uint256 (wei) that the storefront has. /// The true balance will only be revealed to the storeowner who invokes this function. /// Non store owner to this storefront will only see zero for the balance. function getStorefront(bytes32 storefrontUniqueId) public view returns ( string memory storefrontName, address storeOwner, uint256 productsCount, uint256 index, uint256 balance ) { require(storefrontExists(storefrontUniqueId), "storefront does not exist!"); storefrontName = storefronts[storefrontUniqueId].storefrontName; storeOwner = storefronts[storefrontUniqueId].storeOwner; productsCount = storefronts[storefrontUniqueId].productCodes.length; index = storefronts[storefrontUniqueId].index; if (msg.sender == storeOwner) balance = storefronts[storefrontUniqueId].balance; else balance = 0; // Only store owner can access to the balance return (storefrontName, storeOwner, productsCount, index, balance); } /// @notice Check if a storefront exists, using its storefront unique id or hash /// @param uniqueId The storefront unique id or hash /// @return doesExist The boolean result of whether the storefront exists function storefrontExists(bytes32 uniqueId) public view returns (bool doesExist) { if (storefrontIndexes.length == 0) return false; return (storefrontIndexes[storefronts[uniqueId].index] == uniqueId); } /// @notice Check if a product exists by its productCode /// @param productCode The productCode /// @return doesExist The boolean result of whether the product exists function productExists(bytes32 productCode) public view returns (bool doesExist) { if (productIndexes.length == 0) return false; return (productIndexes[products[productCode].index] == productCode); } /// @notice Create a product for a storefront. Only store owner of the storefront /// can invoke this function /// @dev Creating a product involves updating products, productIndexes, /// storefronts' productCodes (array of product codes) and storefront's /// productCodeIndexes (mapping of productCode to index) /// @param storefrontUniqueId The storefront unique id or hash /// @param productCode The product code of the product. /// This should be a hex generated code based on the product name. /// The frontend app should generate this /// @param newProductName The name of the product /// @param price The unit price of the product /// @param availQty The available quantity for the product /// @param infoHash The IPFS hash for accessing the product info stored in IPFS /// @param imageHash The IPFS hash for accessing the product image stored in IPFS /// @return index The index of the created product in uint256 function createProduct( bytes32 storefrontUniqueId, bytes32 productCode, string memory newProductName, uint256 price, uint256 availQty, string memory infoHash, string memory imageHash ) public whenNotPaused onlyStoreOwnerOfStorefront(storefrontUniqueId) returns (uint256 index) { // require(storefrontExists(storefrontUniqueId), "storefront does not exist!"); // require( // storefronts[storefrontUniqueId].storeOwner == msg.sender, // "user is not the storefront owner" // ); require(!productExists(productCode), "Product Code already exists!"); /// Add the productCode into storefront's productCodes array /// and at the same time update the storefront's productCodeIndexes /// with the index of the inserted productCode storefronts[storefrontUniqueId] .productCodeIndexes[productCode] = storefronts[storefrontUniqueId] .productCodes .push(productCode) .sub(1); /// Add the product info into products /// at the same time update productIndexes. /// The product index is derived from the productIndexes.push subtracted by 1 products[productCode].storefrontUniqueId = storefrontUniqueId; products[productCode].name = newProductName; products[productCode].price = price; products[productCode].availQty = availQty; products[productCode].infoHash = infoHash; products[productCode].imageHash = imageHash; products[productCode].index = (productIndexes.push(productCode)).sub(1); emit LogCreateProduct(productCode); return productIndexes.length.sub(1); } /// @notice Update the price of a product. Only the store owner of the storefront /// that owns the product can invoke this function /// @param productCode The product code of the product to be updated /// @param newPrice The new product price to replace the old product price function updateProductPrice(bytes32 productCode, uint256 newPrice) public whenNotPaused onlyStoreOwnerOfProduct(productCode) { //require(productExists(productCode), "Product does not exist!"); // bytes32 storefrontUniqueId = products[productCode].storefrontUniqueId; // require( // msg.sender == storefronts[storefrontUniqueId].storeOwner, // "Only store owner of product can update the price!" // ); products[productCode].price = newPrice; emit LogUpdateProduct(productCode); } /// @notice Delete a product by its productCode. Only the store owner of /// the storefront that owns the product can invoke this function /// @dev Delete requires updates to the products, productIndexes, /// storefront's productCodes and storefront's productIndexes /// @param productCode The productCode of the product to be deleted function deleteProduct(bytes32 productCode) public whenNotPaused onlyStoreOwnerOfProduct(productCode) { //require(productExists(productCode), "Product does not exist!"); // Get the index (uint256) of the productCode of the products mappping // We name this index rowToDelete // We will use this index later to swap position of the last item in the productIndexes array // with the item we want to delete (productCode) in the array uint256 rowToDelete = products[productCode].index; // Get the product code of the last item in the productIndexes array bytes32 keyToMove = productIndexes[productIndexes.length.sub(1)]; // Swap the position of the last item in the productIndexes // with the position of the productCode we want to delete productIndexes[rowToDelete] = keyToMove; products[keyToMove].index = rowToDelete; // Now we delete the last item in the productIndexes which contains the productCode productIndexes.pop(); // Remove the associated productCode stored in the corresponding storefront // First, we get the storefrontUniqueId based on input productCode bytes32 storeId = products[productCode].storefrontUniqueId; // Get the index (uint256) of the productCode of the array productCodes in the storefront // We name this index rowToDelete // We will use this index later to swap position of the last item in the array // with the item we want to delete (productCode) rowToDelete = storefronts[storeId].productCodeIndexes[productCode]; // Get the index of the last item in the array productCodes of the storefront // for the swapping mentioned above uint256 lastIndex = storefronts[storeId].productCodes.length.sub(1); // Get the content (a product code) of the last item in the array productCodes // using the lastIndex we obtained above keyToMove = storefronts[storeId].productCodes[lastIndex]; // Now we swap the content (product code) of the last item with the item we want to delete storefronts[storeId].productCodes[rowToDelete] = keyToMove; storefronts[storeId].productCodes[lastIndex] = productCode; // We also need to update the productCodeIndexes in the storefront // to reflect the swapping took place above storefronts[storeId].productCodeIndexes[keyToMove] = rowToDelete; storefronts[storeId].productCodeIndexes[productCode] = lastIndex; // Now we can remove the last item of the productCodes array which contains the productCode storefronts[storeId].productCodes.pop(); // Also remove the mapping of the productCodeIndexes // Note that deleted mapping would still be referencable but the result would be zero // So the zero result can mean index 0 or no mapping found, keep in mind delete storefronts[storeId].productCodeIndexes[productCode]; // Remove the product from the mapping(bytes32=>ProductStruct) products // We do it here at the end so that fetch the storefrontUniqueId, storeId above delete products[productCode]; emit LogDeleteProduct(productCode); } /// @notice Get the total number of products of all storefronts /// @return count The total number of products of all storefronts in uint256 function getProductsCount() public view returns (uint256 count) { return productIndexes.length; } /// @notice Get product data by its productCode /// @param productCode The product code of the product /// @return productName The name of the product /// @return price The unit price of the product /// @return availQty The available quantity for the product /// @return index The index for accessing this product via productIndexes /// @return infoHash The IPFS hash for accesing the product information /// @return imageHash The IPFS hash for accessing the product image function getProduct(bytes32 productCode) public view returns ( string memory productName, uint256 price, uint256 availQty, uint256 index, string memory infoHash, string memory imageHash ) { require(productExists(productCode), "product does not exist!"); productName = products[productCode].name; price = products[productCode].price; availQty = products[productCode].availQty; index = products[productCode].index; infoHash = products[productCode].infoHash; imageHash = products[productCode].imageHash; return (productName, price, availQty, index, infoHash, imageHash); } /// @notice Get the product data by its index /// @param index The index for accessing the product via productIndexes /// @return productCode The product code of the product /// @return productName The name of the product /// @return price The unit price of the product /// @return availQty The available quantity for the product /// @return infoHash The IPFS hash for accesing the product information /// @return imageHash The IPFS hash for accessing the product image function getProductByIndex(uint256 index) public view returns ( bytes32 productCode, string memory productName, uint256 price, uint256 availQty, string memory infoHash, string memory imageHash ) { productCode = productIndexes[index]; return ( productCode, products[productCode].name, products[productCode].price, products[productCode].availQty, products[productCode].infoHash, products[productCode].imageHash ); } /// @notice Get the storefront's product by product Index /// @param storefrontUniqueId The storefront unique id or hash /// @param index The index for accessing the product data via productCodes /// @return productCode The product code of the product /// @return productName The name of the product /// @return price The unit price of the product /// @return availQty The available quantity for the product /// @return infoHash The IPFS hash for accesing the product information /// @return imageHash The IPFS hash for accessing the product image function getProductForStorefrontByIndex(bytes32 storefrontUniqueId, uint256 index) public view returns ( bytes32 productCode, string memory productName, uint256 price, uint256 availQty, string memory infoHash, string memory imageHash ) { require(storefrontExists(storefrontUniqueId), "storefront does not exist!"); require(storefronts[storefrontUniqueId].productCodes.length > index, "index out of range!"); productCode = storefronts[storefrontUniqueId].productCodes[index]; return ( productCode, products[productCode].name, products[productCode].price, products[productCode].availQty, products[productCode].infoHash, products[productCode].imageHash ); } /// @notice Let shopper buy and pay for a product. If shopper pays more than the required amount, /// the shopper would be refunded. If the shopper tries to pay below the amount required, this /// function would reject it. If the buying quantity is more than the available quantity, this /// function would reject it too. /// @dev OpenZeppelin SafeMath is used here to prevent overflow or underflow /// @param productCode The product code of the product that the shopper is buying or paying for /// @param buyQty The quantity of the product the shopper wants to buy or pay for function buyProduct(bytes32 productCode, uint256 buyQty) public payable whenNotPaused { require(productExists(productCode), "Product does not exist!"); require(buyQty > 0, "Buy quantity must be more than zero!"); uint256 price = products[productCode].price; uint256 availQty = products[productCode].availQty; uint256 amountPayable = price.mul(buyQty); uint256 refund = 0; if (msg.value > amountPayable) { refund = msg.value.sub(amountPayable); } require(buyQty <= availQty, "Buy quantity is more than the available quantity!"); require(msg.value >= amountPayable, "Insufficient funds to complete transaction!"); bytes32 uniqueId = products[productCode].storefrontUniqueId; storefronts[uniqueId].balance = storefronts[uniqueId].balance.add(amountPayable); /// Deduct the available quantity of the product products[productCode].availQty = products[productCode].availQty.sub(buyQty); emit LogBuyProduct(msg.sender, productCode); /// If there's refund to be made, do it now if (refund > 0) { msg.sender.transfer(refund); } } /// @notice Withdraw the balance from a storefront, /// if the balance is more than zero. Only store owner of the storefront /// can invoke this function /// @param storefrontUniqueId The storefront unique id or hash /// @return success The boolean result whether the withdrawal is successful function withdrawBalanceFromStorefront(bytes32 storefrontUniqueId) public whenNotPaused returns (bool success) { require(storefrontExists(storefrontUniqueId), "Storefront does not exist!"); require( msg.sender == storefronts[storefrontUniqueId].storeOwner, "Must be the owner to withdraw balance!" ); uint256 balanceToWithdraw = storefronts[storefrontUniqueId].balance; require(balanceToWithdraw > 0, "The balance must be more than zero to withdraw!"); storefronts[storefrontUniqueId].balance = (storefronts[storefrontUniqueId].balance).sub( balanceToWithdraw ); emit LogWithdrawBalanceFromStorefront(storefrontUniqueId); msg.sender.transfer(balanceToWithdraw); // transfer balance back to store owner return true; } /// Fallback function function() external { revert(""); } }
Get a store owner's data by store owner's address addr The address of the store owner return storeOwnerAddr The address of the store owner return storeOwnerName The store owner name return storefrontsCount The total number of storefronts the store owner has
function getStoreOwner(address addr) public view returns (uint256 storeOwnerIndex, string memory storeOwnerName, uint256 storefrontsCount) { storeOwnerIndex = storeOwners[addr].index; storeOwnerName = storeOwners[addr].name; storefrontsCount = storeOwners[addr].storefrontUniqueIds.length; return (storeOwnerIndex, storeOwnerName, storefrontsCount); }
14,112,197
./full_match/80001/0xE7539a624FB9115aaF8Bf0433Ed8a6e39E2805e3/sources/contracts/Winners.sol
Distribui o saldo para todos os usuários se for um novo depósito
function distributeBalance(bool newDeposit) internal { emit Log("distributeBalance called"); if (rankingAddresses.length == 0 || address(this).balance == 0) { return; } if (address(this).balance >= distributeStart) { uint256 amount = newDeposit ? lastDepositAmount : address(this).balance; uint256 numUsers = rankingAddresses.length; uint256 amountForTopUsers = amount.mul(99).div(100); uint256 amountPerTopUser = amountForTopUsers.div(99); uint256 amountForNonTopUsers = amount.sub(amountForTopUsers); uint256 amountPerNonTopUser = numUsers >= 100 ? amountForNonTopUsers.div(numUsers.sub(99)) : amountForNonTopUsers; for (uint256 i = 0; i < rankingAddresses.length; i++) { address user = rankingAddresses[i]; if (newDeposit || distributedBalances[user] == 0) { uint256 transferAmount = rankingIndex[user] < 100 ? amountPerTopUser : amountPerNonTopUser; transferAmount = transferAmount.div(1e15).mul(1e15); if (totalDistributed.add(transferAmount) > address(this).balance) { transferAmount = address(this).balance.sub(totalDistributed); } balances[user] = balances[user].add(transferAmount); distributedBalances[user] = transferAmount; totalDistributed = totalDistributed.add(transferAmount); emit SplitBalances(user, amount); } } } }
5,690,390
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./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 pragma solidity >=0.7.0; import "../interfaces/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; library Strings { function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC1155.sol"; import "../interfaces/IERC1155MetadataURI.sol"; import "../interfaces//IERC1155Receiver.sol"; import "../utils/Context.sol"; import "../introspection/ERC165.sol"; import "../libs/SafeMath.sol"; import "../utils/Address.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 SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _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}. */ constructor(string memory uri_) { _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) external 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 { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_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(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _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: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); 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 for transfer"); _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 `account` 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: mint to the 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: 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].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: ids and amounts 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 ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).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 ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).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) internal pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./ERC1155.sol"; import "../utils/Pausable.sol"; /** * @dev ERC1155 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IERC1155Receiver.sol"; import "../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/Strings.sol"; import "../libs/SafeMath.sol"; import "./ERC1155Pausable.sol"; import "./ERC1155Holder.sol"; import "../access/Controllable.sol"; import "../interfaces/INFTGemMultiToken.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract NFTGemMultiToken is ERC1155Pausable, ERC1155Holder, INFTGemMultiToken, Controllable { using SafeMath for uint256; using Strings for string; // allows opensea to address private constant OPENSEA_REGISTRY_ADDRESS = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; address[] private proxyRegistries; address private registryManager; mapping(uint256 => uint256) private _totalBalances; mapping(address => mapping(uint256 => uint256)) private _tokenLocks; mapping(address => uint256[]) private _heldTokens; mapping(uint256 => address[]) private _tokenHolders; /** * @dev Contract initializer. */ constructor() ERC1155("https://metadata.bitgem.co/") { _addController(msg.sender); registryManager = msg.sender; proxyRegistries.push(OPENSEA_REGISTRY_ADDRESS); } function lock(uint256 token, uint256 timestamp) external override { require(_tokenLocks[_msgSender()][token] < timestamp, "ALREADY_LOCKED"); _tokenLocks[_msgSender()][timestamp] = timestamp; } function unlockTime(address account, uint256 token) external view override returns (uint256 theTime) { theTime = _tokenLocks[account][token]; } /** * @dev Returns the metadata URI for this token type */ function uri(uint256 _id) public view override(ERC1155) returns (string memory) { require(_totalBalances[_id] != 0, "NFTGemMultiToken#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(ERC1155Pausable(this).uri(_id), Strings.uint2str(_id)); } /** * @dev Returns the total balance minted of this type */ function allHeldTokens(address holder, uint256 _idx) external view override returns (uint256) { return _heldTokens[holder][_idx]; } /** * @dev Returns the total balance minted of this type */ function allHeldTokensLength(address holder) external view override returns (uint256) { return _heldTokens[holder].length; } /** * @dev Returns the total balance minted of this type */ function allTokenHolders(uint256 _token, uint256 _idx) external view override returns (address) { return _tokenHolders[_token][_idx]; } /** * @dev Returns the total balance minted of this type */ function allTokenHoldersLength(uint256 _token) external view override returns (uint256) { return _tokenHolders[_token].length; } /** * @dev Returns the total balance minted of this type */ function totalBalances(uint256 _id) external view override returns (uint256) { return _totalBalances[_id]; } /** * @dev Returns the total balance minted of this type */ function allProxyRegistries(uint256 _idx) external view override returns (address) { return proxyRegistries[_idx]; } /** * @dev Returns the total balance minted of this type */ function getRegistryManager() external view override returns (address) { return registryManager; } /** * @dev Returns the total balance minted of this type */ function setRegistryManager(address newManager) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(newManager != address(0), "UNAUTHORIZED"); registryManager = newManager; } /** * @dev Returns the total balance minted of this type */ function allProxyRegistriesLength() external view override returns (uint256) { return proxyRegistries.length; } /** * @dev Returns the total balance minted of this type */ function addProxyRegistry(address registry) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); proxyRegistries.push(registry); } /** * @dev Returns the total balance minted of this type */ function removeProxyRegistryAt(uint256 index) external override { require(msg.sender == registryManager, "UNAUTHORIZED"); require(index < proxyRegistries.length, "INVALID_INDEX"); proxyRegistries[index] = proxyRegistries[proxyRegistries.length - 1]; delete proxyRegistries[proxyRegistries.length - 1]; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. for(uint256 i = 0; i < proxyRegistries.length; i++) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistries[i]); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev mint some amount of tokens. Only callable by token owner */ function mint( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _mint(account, uint256(tokenHash), amount, "0x0"); } /** * @dev internal mint overridden to manage token holders and held tokens lists */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); } /** * @dev internal minttbatch should account for managing lists */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); } /** * @dev mint some amount of tokens. Only callable by token owner */ function burn( address account, uint256 tokenHash, uint256 amount ) external override onlyController { _burn(account, uint256(tokenHash), amount); } /** * @dev internal burn overridden to track lists */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); } /** * @dev internal burnBatch should account for managing lists */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); } /** * @dev intercepting token transfers to manage a list of zero-token holders */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { // prevent send if tokens are locked if (from != address(0)) { require(_tokenLocks[from][ids[i]] <= block.timestamp, "TOKEN_LOCKED"); } // if this is not a mint then remove the held token id from lists if // this is the last token if this type the sender owns if (from != address(0) && balanceOf(from, ids[i]) - amounts[i] == 0) { // remove from heldTokens for (uint256 j = 0; j < _heldTokens[from].length; j++) { if (_heldTokens[from][j] == ids[i]) { _heldTokens[from][j] = _heldTokens[from][_heldTokens[from].length - 1]; delete _heldTokens[from][_heldTokens[from].length - 1]; } } // remove from tokenHolders for (uint256 j = 0; j < _tokenHolders[ids[i]].length; j++) { if (_tokenHolders[ids[i]][j] == from) { _tokenHolders[ids[i]][j] = _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; delete _tokenHolders[ids[i]][_tokenHolders[ids[i]].length - 1]; } } } // if this is not a burn and receiver does not yet own token then // add that account to the token for that id if (to != address(0) && balanceOf(to, ids[i]) == 0) { _heldTokens[to].push(ids[i]); _tokenHolders[ids[i]].push(to); } // inc and dec balances for each token type if (from == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].add(amounts[i]); } if (to == address(0)) { _totalBalances[uint256(ids[i])] = _totalBalances[uint256(ids[i])].sub(amounts[i]); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.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.7.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
See {IERC1155-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); }
1,317,889
./partial_match/1/0xfE4D7937B3528fE84aE5981e4883c91Ac0f901F8/sources/contracts/reflection/standard/BabyPsyop.sol
Allows users to claim their pending rewards if they are not excluded from rewards. Calls the internal processRewards function to calculate and distribute rewards based on the user's balance, eligible rewards, and adjusted supply./
function claim() external { if (isExcludedFromRewards.contains(msg.sender)) { revert Blocked(); } processRewards(msg.sender, balanceOf(msg.sender), rewards[msg.sender], getAdjustedSupply()); }
2,873,641
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Bank * @dev Store tokens and compound savings */ contract Bank { // ------------------------------------------------------------------ // config address public owner; address public tokenAddress; uint256 public compoundPercentage; uint256 public compoundPeriod; uint256 public maxCompoundReturn; /** * @dev Set contract deployer as owner * @param _tokenAddress ERC20 token address * @param _compoundPercentage savings compounding percentage * @param _compoundPeriod seconds since last savings before compounding * @param _maxCompoundReturn maximum amount of compounding on savings */ constructor( address _tokenAddress, uint256 _compoundPercentage, uint256 _compoundPeriod, uint256 _maxCompoundReturn ) { owner = msg.sender; tokenAddress = _tokenAddress; compoundPercentage = _compoundPercentage; compoundPeriod = _compoundPeriod; maxCompoundReturn = _maxCompoundReturn; } // ------------------------------------------------------------------ // structs struct Account { uint256 balance; uint256 savings; uint256 savingsDate; } // ------------------------------------------------------------------ // state mapping(address => Account) private accounts; // ------------------------------------------------------------------ // owner events event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenChanged(address indexed previousToken, address indexed newToken); event CompoundPercentageChanged( uint256 previousPercentage, uint256 newPercentage ); event CompoundPeriodChanged(uint256 previousPeriod, uint256 newPeriod); // ------------------------------------------------------------------ // user events event Deposit(address indexed account, uint256 amount); event Withdraw(address indexed account, uint256 amount); event Save(address indexed account, uint256 amount); event Unsave(address indexed account, uint256 amount); event Compound( address indexed account, string indexed compoundType, uint256 amount ); // ------------------------------------------------------------------ // modifiers modifier isOwner() { require(msg.sender == owner, "Caller is not owner"); _; } modifier hasBalance(uint256 _amount) { require(accounts[msg.sender].balance >= _amount, "Balance too low"); _; } modifier hasSavings(uint256 _amount) { require(accounts[msg.sender].savings >= _amount, "Savings too low"); _; } modifier isLockPeriodPast() { require( block.timestamp > accounts[msg.sender].savingsDate + compoundPeriod, "Savings lock period not over yet" ); _; } // ------------------------------------------------------------------ // Helper functions /** * @dev Returns the token implementation * @return _token ERC-20 token */ function getToken() internal view returns (IERC20 _token) { return IERC20(tokenAddress); } /** * @dev Returns the token implementation * @return _compoundReturn Capped return for compounding */ function calculateCappedCompoundReturn(uint256 savings) internal view returns (uint256 _compoundReturn) { uint256 compoundValue = (savings / 100) * compoundPercentage; uint256 valueWithCap = compoundValue > maxCompoundReturn ? maxCompoundReturn : compoundValue; return valueWithCap; } // ------------------------------------------------------------------ // Owner functions /** * @dev Set owner * @param _owner new owner address */ function setOwner(address _owner) public isOwner { emit OwnerChanged(owner, _owner); owner = _owner; } /** * @dev Set compound percentage * @param _compoundPercentage savings compounding percentage */ function setCompoundPercentage(uint256 _compoundPercentage) public isOwner { emit CompoundPercentageChanged(compoundPercentage, _compoundPercentage); compoundPercentage = _compoundPercentage; } /** * @dev Set compound period * @param _compoundPeriod seconds since last savings before compounding */ function setCompoundPeriod(uint256 _compoundPeriod) public isOwner { emit CompoundPeriodChanged(compoundPeriod, _compoundPeriod); compoundPeriod = _compoundPeriod; } // ------------------------------------------------------------------ // User functions /** * @dev Deposit to caller's balance * @param _amount amount of tokens to deposit */ function deposit(uint256 _amount) public { IERC20 token = getToken(); token.transferFrom(msg.sender, address(this), _amount); accounts[msg.sender].balance += _amount; emit Deposit(msg.sender, _amount); } /** * @dev Withdraw from caller's balance * @param _amount amount of tokens to withdraw */ function withdraw(uint256 _amount) public hasBalance(_amount) { IERC20 token = getToken(); token.transfer(msg.sender, _amount); accounts[msg.sender].balance -= _amount; emit Withdraw(msg.sender, _amount); } /** * @dev Move tokens from balance to savings * @param _amount amount of tokens to transfer */ function save(uint256 _amount) public hasBalance(_amount) { accounts[msg.sender].balance -= _amount; accounts[msg.sender].savings += _amount; accounts[msg.sender].savingsDate = block.timestamp; emit Save(msg.sender, _amount); } /** * @dev Move tokens from savings to balance * @dev Only allowed when savings lock period is past * @param _amount amount of tokens to transfer */ function unsave(uint256 _amount) public hasSavings(_amount) isLockPeriodPast { accounts[msg.sender].balance += _amount; accounts[msg.sender].savings -= _amount; emit Unsave(msg.sender, _amount); } /** * @dev Compound savings and save the returns * @dev Only allowed when savings lock period is past * @dev Compound value capped to maxCompoundReturn */ function compoundAndSave() public isLockPeriodPast { uint256 valueWithCap = calculateCappedCompoundReturn( accounts[msg.sender].savings ); accounts[msg.sender].savings += valueWithCap; accounts[msg.sender].savingsDate = block.timestamp; emit Compound(msg.sender, "Save", valueWithCap); } /** * @dev Compound savings and withdraw the returns * @dev Only allowed when savings lock period is past * @dev Compound value capped to maxCompoundReturn */ function compoundAndWithdrawReturns() public isLockPeriodPast { uint256 valueWithCap = calculateCappedCompoundReturn( accounts[msg.sender].savings ); accounts[msg.sender].balance += valueWithCap; accounts[msg.sender].savingsDate = block.timestamp; emit Compound(msg.sender, "WithdrawReturns", valueWithCap); } /** * @dev Compound savings and withdraw savings and returns * @dev Only allowed when savings lock period is past * @dev Compound value capped to maxCompoundReturn */ function compoundAndWithdrawAll() public isLockPeriodPast { uint256 valueWithCap = calculateCappedCompoundReturn( accounts[msg.sender].savings ); accounts[msg.sender].balance += accounts[msg.sender].savings + valueWithCap; accounts[msg.sender].savings = 0; accounts[msg.sender].savingsDate = block.timestamp; emit Compound(msg.sender, "WithdrawAll", valueWithCap); } // ------------------------------------------------------------------ // View functions /** * @dev Return account * @return _account account */ function getAccount() external view returns (Account memory _account) { return accounts[msg.sender]; } /** * @dev Return account balance * @return _balance account balance */ function getBalance() external view returns (uint256 _balance) { return accounts[msg.sender].balance; } /** * @dev Return account savings * @return _savings account savings */ function getSavings() external view returns (uint256 _savings) { return accounts[msg.sender].savings; } /** * @dev Return savings timestamp * @return _date savings timestamp */ function getSavingsDate() external view returns (uint256 _date) { return accounts[msg.sender].savingsDate; } }
Withdraw from caller's balance _amount amount of tokens to withdraw/
function withdraw(uint256 _amount) public hasBalance(_amount) { IERC20 token = getToken(); token.transfer(msg.sender, _amount); accounts[msg.sender].balance -= _amount; emit Withdraw(msg.sender, _amount); }
15,823,244
./full_match/1/0x71a734f01270199D31D3ebB6174569A7cFf3d54a/sources/contracts/auction/Auction.sol
gets user's bid
function getUserBid(address bidder) external view returns (uint256 bidAmount) { return userBid[bidder].amount; }
9,689,071
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; import './interfaces/IDexPriceAggregator.sol'; import './libraries/SafeCast.sol'; import './Owned.sol'; /// @title DexPriceAggregatorUniswapV3 /// @notice A DexPriceAggregator sourcing prices from Uniswap V3. /// Provides the minimum output between an asset's "spot" price and TWAP from the last n seconds. /// The "spot" price is always the last block's ending price. contract DexPriceAggregatorUniswapV3 is IDexPriceAggregator, Owned { address public immutable uniswapV3Factory; address public immutable weth; uint24 public immutable defaultPoolFee; mapping(bytes32 => address) public overriddenPoolForRoute; constructor( address _owner, address _uniswapV3Factory, address _weth, uint24 _defaultPoolFee ) Owned(_owner) { uniswapV3Factory = _uniswapV3Factory; weth = _weth; defaultPoolFee = _defaultPoolFee; } /******************** * Oracle functions * ********************/ /// @inheritdoc IDexPriceAggregator function assetToAsset( address _tokenIn, uint256 _amountIn, address _tokenOut, uint256 _twapPeriod ) public view override returns (uint256 amountOut) { if (_tokenIn == weth) { return ethToAsset(_amountIn, _tokenOut, _twapPeriod); } else if (_tokenOut == weth) { return assetToEth(_tokenIn, _amountIn, _twapPeriod); } else { return _fetchAmountCrossingPools(_tokenIn, _amountIn, _tokenOut, _twapPeriod); } } /// @notice Given a token and its amount, return the equivalent value in ETH /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return ethAmountOut Amount of ETH received for amountIn of tokenIn function assetToEth( address _tokenIn, uint256 _amountIn, uint256 _twapPeriod ) public view returns (uint256 ethAmountOut) { address tokenOut = weth; address pool = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, tokenOut, defaultPoolFee)); return _fetchAmountFromSinglePool(_tokenIn, _amountIn, tokenOut, pool, _twapPeriod); } /// @notice Given an amount of ETH, return the equivalent value in another token /// @param _ethAmountIn Amount of ETH to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of tokenOut received for ethAmountIn of ETH function ethToAsset( uint256 _ethAmountIn, address _tokenOut, uint256 _twapPeriod ) public view returns (uint256 amountOut) { address tokenIn = weth; address pool = _getPoolForRoute(PoolAddress.getPoolKey(tokenIn, _tokenOut, defaultPoolFee)); return _fetchAmountFromSinglePool(tokenIn, _ethAmountIn, _tokenOut, pool, _twapPeriod); } /************************ * Management functions * ************************/ /// @notice Override the Uniswap V3 pool queried on a tokenA:tokenB route /// @dev Override can be reset by using address(0) for _pool /// @param _tokenA Address of an ERC20 token contract /// @param _tokenB Address of another ERC20 token contract /// @param _pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB function setPoolForRoute( address _tokenA, address _tokenB, address _pool ) public onlyOwner { PoolAddress.PoolKey memory poolKey = PoolAddress.getPoolKey( _tokenA, _tokenB, uint24(0) // pool fee is unused ); if (_pool != address(0)) { require( poolKey.token0 == IUniswapV3Pool(_pool).token0() && poolKey.token1 == IUniswapV3Pool(_pool).token1(), 'Tokens or pool not correct' ); } overriddenPoolForRoute[_identifyRouteFromPoolKey(poolKey)] = _pool; emit PoolForRouteSet(poolKey.token0, poolKey.token1, _pool); } /// @notice Fetch the Uniswap V3 pool to be queried for a tokenA:tokenB route /// @param _tokenA Address of an ERC20 token contract /// @param _tokenB Address of another ERC20 token contract /// @return pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB function getPoolForRoute(address _tokenA, address _tokenB) public view returns (address pool) { return _getPoolForRoute(PoolAddress.getPoolKey(_tokenA, _tokenB, defaultPoolFee)); } /************************** * Utility view functions * **************************/ /// @notice Fetch a Uniswap V3 pool's current "spot" and TWAP tick values /// @param _pool Address of a Uniswap V3 pool /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return spotTick The pool's current "spot" tick /// @return twapTick The twap tick for the last _twapPeriod seconds function fetchCurrentTicks(address _pool, uint32 _twapPeriod) public view returns (int24 spotTick, int24 twapTick) { spotTick = OracleLibrary.getBlockStartingTick(_pool); twapTick = OracleLibrary.consult(_pool, _twapPeriod); } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick Tick value representing conversion ratio between _tokenIn and _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function getQuoteAtTick( address _tokenIn, uint128 _amountIn, address _tokenOut, int24 _tick ) public pure returns (uint256 amountOut) { return OracleLibrary.getQuoteAtTick(_tick, _amountIn, _tokenIn, _tokenOut); } /// @notice Similar to getQuoteAtTick() but calculates the amount of token received in exchange /// by first adjusting into ETH /// (ie. when a route goes through an intermediary pool with ETH) /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick1 First tick value representing conversion ratio between _tokenIn and ETH /// @param _tick2 Second tick value representing conversion ratio between ETH and _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function getQuoteCrossingTicksThroughWeth( address _tokenIn, uint128 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) public view returns (uint256 amountOut) { return _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, _tick1, _tick2); } /************* * Internals * *************/ /// @notice Given a token and amount, return the equivalent value in another token by exchanging /// within a single liquidity pool /// @dev _pool _must_ be previously checked to contain _tokenIn and _tokenOut. /// It is exposed as a parameter only as a gas optimization. /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _pool Address of a Uniswap V3 pool containing _tokenIn and _tokenOut /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _fetchAmountFromSinglePool( address _tokenIn, uint256 _amountIn, address _tokenOut, address _pool, uint256 _twapPeriod ) internal view returns (uint256 amountOut) { // Leave ticks as int256s to avoid solidity casting int256 spotTick = OracleLibrary.getBlockStartingTick(_pool); int256 twapTick = OracleLibrary.consult(_pool, SafeCast.toUint32(_twapPeriod)); // Return min amount between spot price and twap // Ticks are based on the ratio between token0:token1 so if the input token is token1 then // we need to treat the tick as an inverse int256 minTick; if (_tokenIn < _tokenOut) { minTick = spotTick < twapTick ? spotTick : twapTick; } else { minTick = spotTick > twapTick ? spotTick : twapTick; } return OracleLibrary.getQuoteAtTick( int24(minTick), // can assume safe being result from consult() SafeCast.toUint128(_amountIn), _tokenIn, _tokenOut ); } /// @notice Given a token and amount, return the equivalent value in another token by "crossing" /// liquidity across an intermediary pool with ETH (ie. _tokenIn:ETH and ETH:_tokenOut) /// @dev If an overridden pool has been set for _tokenIn and _tokenOut, this pool will be used /// used directly in lieu of "crossing" against an intermediary pool with ETH /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _fetchAmountCrossingPools( address _tokenIn, uint256 _amountIn, address _tokenOut, uint256 _twapPeriod ) internal view returns (uint256 amountOut) { // If the tokenIn:tokenOut route was overridden to use a single pool, derive price directly from that pool address overriddenPool = _getOverriddenPool( PoolAddress.getPoolKey( _tokenIn, _tokenOut, uint24(0) // pool fee is unused ) ); if (overriddenPool != address(0)) { return _fetchAmountFromSinglePool(_tokenIn, _amountIn, _tokenOut, overriddenPool, _twapPeriod); } // Otherwise, derive the price by "crossing" through tokenIn:ETH -> ETH:tokenOut // To keep consistency, we cross through with the same price source (spot vs. twap) address pool1 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, weth, defaultPoolFee)); address pool2 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenOut, weth, defaultPoolFee)); int24 spotTick1 = OracleLibrary.getBlockStartingTick(pool1); int24 spotTick2 = OracleLibrary.getBlockStartingTick(pool2); uint256 spotAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, spotTick1, spotTick2); uint32 castedTwapPeriod = SafeCast.toUint32(_twapPeriod); int24 twapTick1 = OracleLibrary.consult(pool1, castedTwapPeriod); int24 twapTick2 = OracleLibrary.consult(pool2, castedTwapPeriod); uint256 twapAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, twapTick1, twapTick2); // Return min amount between spot price and twap return spotAmountOut < twapAmountOut ? spotAmountOut : twapAmountOut; } /// @notice Similar to OracleLibrary#getQuoteAtTick but calculates the amount of token received /// in exchange by first adjusting into ETH /// (ie. when a route goes through an intermediary pool with ETH) /// @param _tokenIn Address of an ERC20 token contract to be converted /// @param _amountIn Amount of tokenIn to be converted /// @param _tokenOut Address of an ERC20 token contract to convert into /// @param _tick1 First tick value used to adjust from _tokenIn to ETH /// @param _tick2 Second tick value used to adjust from ETH to _tokenOut /// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn function _getQuoteCrossingTicksThroughWeth( address _tokenIn, uint256 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) internal view returns (uint256 amountOut) { uint256 ethAmountOut = OracleLibrary.getQuoteAtTick(_tick1, SafeCast.toUint128(_amountIn), _tokenIn, weth); return OracleLibrary.getQuoteAtTick(_tick2, SafeCast.toUint128(ethAmountOut), weth, _tokenOut); } /// @notice Fetch the Uniswap V3 pool to be queried for a route denoted by a PoolKey /// @param _poolKey PoolKey representing the route /// @return pool Address of the Uniswap V3 pool to use for the route function _getPoolForRoute(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { pool = _getOverriddenPool(_poolKey); if (pool == address(0)) { pool = PoolAddress.computeAddress(uniswapV3Factory, _poolKey); } } /// @notice Obtain the canonical identifier for a route denoted by a PoolKey /// @param _poolKey PoolKey representing the route /// @return id identifier for the route function _identifyRouteFromPoolKey(PoolAddress.PoolKey memory _poolKey) internal pure returns (bytes32 id) { return keccak256(abi.encodePacked(_poolKey.token0, _poolKey.token1)); } /// @notice Fetch an overridden pool for a route denoted by a PoolKey, if any /// @param _poolKey PoolKey representing the route /// @return pool Address of the Uniswap V3 pool overridden for the route. /// address(0) if no overridden pool has been set. function _getOverriddenPool(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) { return overriddenPoolForRoute[_identifyRouteFromPoolKey(_poolKey)]; } /********** * Events * **********/ event PoolForRouteSet(address indexed token0, address indexed token1, address indexed pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol'; import '../libraries/PoolAddress.sol'; /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / period); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo(address pool) internal view returns (uint32) { (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, 'NI'); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } return uint32(block.timestamp) - observationTimestamp; } /// @notice Given a pool, it returns the tick value as of the start of the current block /// @param pool Address of Uniswap V3 pool /// @return The tick that the pool was in at the start of the current block function getBlockStartingTick(address pool) internal view returns (int24) { (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); // 2 observations are needed to reliably calculate the block starting tick require(observationCardinality > 1, 'NEO'); // If the latest observation occurred in the past, then no tick-changing trades have happened in this block // therefore the tick in `slot0` is the same as at the beginning of the current block. // We don't need to check if this observation is initialized - it is guaranteed to be. (uint32 observationTimestamp, int56 tickCumulative, , ) = IUniswapV3Pool(pool).observations(observationIndex); if (observationTimestamp != uint32(block.timestamp)) { return tick; } uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality; (uint32 prevObservationTimestamp, int56 prevTickCumulative, , bool prevInitialized) = IUniswapV3Pool(pool).observations(prevIndex); require(prevInitialized, 'ONI'); return int24((tickCumulative - prevTickCumulative) / (observationTimestamp - prevObservationTimestamp)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title DexPriceAggregator interface /// @notice Provides interface for querying an asset's price from one or more DEXes interface IDexPriceAggregator { /// @notice Given a token and its amount, return the equivalent value in another token /// @param tokenIn Address of an ERC20 token contract to be converted /// @param amountIn Amount of tokenIn to be converted /// @param tokenOut Address of an ERC20 token contract to convert into /// @param twapPeriod Number of seconds in the past to consider for the TWAP rate, if applicable /// @return amountOut Amount of tokenOut received for amountIn of tokenIn function assetToAsset( address tokenIn, uint256 amountIn, address tokenOut, uint256 twapPeriod ) external view returns (uint256 amountOut); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types /// Adapted from UniswapV3: https://github.com/Uniswap/uniswap-v3-core/blob/v1.0.0/contracts/libraries/SafeCast.sol library SafeCast { /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a uint256 to a uint32, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint32 function toUint32(uint256 y) internal pure returns (uint32 z) { require((z = uint32(y)) == y); } } // SPDX-License-Identifier: MIT // Adapted from https://github.com/Synthetixio/synthetix/blob/v2.46.0/contracts/Owned.sol pragma solidity >=0.5.0 <0.8.0; /// @title Only-owner utility /// @notice Provides subclasses with only-owner permission utilities abstract contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) { require(_owner != address(0), 'Owner address cannot be 0'); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, 'You must be nominated before you can accept ownership'); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner() { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, 'Only the contract owner may perform this action'); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } }
Similar to OracleLibrarygetQuoteAtTick but calculates the amount of token received in exchange by first adjusting into ETH (ie. when a route goes through an intermediary pool with ETH) _tokenIn Address of an ERC20 token contract to be converted _amountIn Amount of tokenIn to be converted _tokenOut Address of an ERC20 token contract to convert into _tick1 First tick value used to adjust from _tokenIn to ETH _tick2 Second tick value used to adjust from ETH to _tokenOut return amountOut Amount of _tokenOut received for _amountIn of _tokenIn
function _getQuoteCrossingTicksThroughWeth( address _tokenIn, uint256 _amountIn, address _tokenOut, int24 _tick1, int24 _tick2 ) internal view returns (uint256 amountOut) { uint256 ethAmountOut = OracleLibrary.getQuoteAtTick(_tick1, SafeCast.toUint128(_amountIn), _tokenIn, weth); return OracleLibrary.getQuoteAtTick(_tick2, SafeCast.toUint128(ethAmountOut), weth, _tokenOut); }
1,180,857
pragma solidity ^0.6.0; // SPDX-License-Identifier: UNLICENSED /** * @title SafeMath * @dev Math operations with safety checks that throw on error * */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- interface IERC20 { function transfer(address to, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // 'MCORE' token AND staking contract // Symbol : MCORE // Name : MetaCore // Total supply: 7000 (7 thousands) // Decimals : 18 // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract MetaCore is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "MCORE"; string public name = "MetaCore"; uint256 public decimals = 18; uint256 _totalSupply = 7e3 * 10 ** (decimals); uint256 deployTime; uint256 private totalDividentPoints; uint256 pointMultiplier = 1000000000000000000; uint256 public stakedCoins; uint256 public totalRewardsClaimed; address uniSwapAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address MCORE_WETH_POOL_ADDRESS = address(0); address devs; address communityFund; struct Account { uint256 balance; uint256 lastDividentPoints; uint256 timeInvest; uint256 lastClaimed; uint256 rewardsClaimed; uint256 totalStakes; uint256 pending; } mapping(address => Account) accounts; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = 0xcC3d0B03DCC7C2d4f7C71E4DAFDb1C40A4829Df5; devs = 0x81B794fad3BC654C8662614e83750E3541591fE5; communityFund = 0x9F2742e7427E26DeC6beD359F0B4b5bff6A41bB3; balances[communityFund] = totalSupply(); // 7000 emit Transfer(address(0), communityFund, totalSupply()); deployTime = block.timestamp; } function setLpsAddress(address _MCORE_WETH_POOL_ADDRESS) external onlyOwner{ require(_MCORE_WETH_POOL_ADDRESS != address(0), "Pool address cannot be zero"); require(MCORE_WETH_POOL_ADDRESS == address(0), "Pool address already set"); MCORE_WETH_POOL_ADDRESS = _MCORE_WETH_POOL_ADDRESS; } // ------------------------------------------------------------------------ // Stake the 'MCORE-WETH Lp' tokens to earn reward in 'MCORE'tokens // ------------------------------------------------------------------------ function STAKE(uint256 _tokens) external returns(bool){ require(IERC20(MCORE_WETH_POOL_ADDRESS).transferFrom(msg.sender, address(this), _tokens), "Insufficient Tokens!"); stakedCoins = stakedCoins.add(_tokens); // MCORE_WETH Lp uint256 owing = dividendsOwing(msg.sender); // MCORE tokens if(owing > 0) { // checks previous pending rewards accounts[msg.sender].pending = owing; } accounts[msg.sender].balance = accounts[msg.sender].balance.add(_tokens); // MCORE_WETH Lp accounts[msg.sender].lastDividentPoints = totalDividentPoints; // MCORE tokens accounts[msg.sender].timeInvest = now; accounts[msg.sender].lastClaimed = now; accounts[msg.sender].totalStakes = accounts[msg.sender].totalStakes.add(_tokens); // MCORE_WETH Lp return true; } // ------------------------------------------------------------------------ // Gives the tokens in MCORE - ready to claim // ------------------------------------------------------------------------ function pendingReward(address _user) external view returns(uint256 MCORE){ uint256 owing = dividendsOwing(_user); return owing; } // ------------------------------------------------------------------------ // internal function used when MCORE tokens reward is claimed // ------------------------------------------------------------------------ function updateDividend(address investor) internal returns(uint256){ uint256 owing = dividendsOwing(investor); // MCORE tokens if (owing > 0){ accounts[investor].lastDividentPoints = totalDividentPoints; } return owing; } // ------------------------------------------------------------------------ // Gives the MCORE_WETH Lp tokens actively staked by the user // ------------------------------------------------------------------------ function activeStake(address _user) external view returns (uint256){ return accounts[_user].balance; } // ------------------------------------------------------------------------ // Gives the MCORE_WETH Lp tokens staked by the user till the current date // ------------------------------------------------------------------------ function totalStakesTillToday(address _user) external view returns (uint256){ return accounts[_user].totalStakes; } // ------------------------------------------------------------------------ // Used to stop the staking and get back MCORE_WETH Lp Tokens // ------------------------------------------------------------------------ function UNSTAKE() external returns (bool){ require(stakedCoins > 0); // MCORE_WETH Lp require(accounts[msg.sender].balance > 0); // MCORE_WETH Lp uint256 owing = dividendsOwing(msg.sender); // MCORE tokens if(owing > 0) { // checks previous pending rewards accounts[msg.sender].pending = owing; } stakedCoins = stakedCoins.sub(accounts[msg.sender].balance); // MCORE_WETH Lp require(IERC20(MCORE_WETH_POOL_ADDRESS).transfer(msg.sender, accounts[msg.sender].balance)); // sends the lp tokens back from the contract to the investor accounts[msg.sender].balance = 0; // reset the balance of the investor return true; } // ------------------------------------------------------------------------------- // Internal function used to disburse the MCORE tokens among all Lp tokens staked // ------------------------------------------------------------------------------- function disburse(uint256 amount) internal{ uint256 unnormalized = amount.mul(pointMultiplier); totalDividentPoints = totalDividentPoints.add(unnormalized.div(stakedCoins)); // stakedCoins is the MCORE_WETH lp tokens } // ------------------------------------------------------------------------------- // Internal function gives how much MCORE tokens reward is ready to be claimed // ------------------------------------------------------------------------------- function dividendsOwing(address investor) internal view returns (uint256){ uint256 newDividendPoints = totalDividentPoints.sub(accounts[investor].lastDividentPoints); return (((accounts[investor].balance).mul(newDividendPoints)).div(pointMultiplier)).add(accounts[investor].pending); } // ------------------------------------------------------------------------------- // Used to claim the reward in MCORE tokens // ------------------------------------------------------------------------------- function claimReward() external returns(bool){ uint256 owing = updateDividend(msg.sender); // MCORE tokens ready to be claimed require(_transfer(msg.sender, owing)); accounts[msg.sender].rewardsClaimed = accounts[msg.sender].rewardsClaimed.add(owing); totalRewardsClaimed = totalRewardsClaimed.add(owing); return true; } function rewardsClaimed(address _user) external view returns(uint256 rewardClaimed){ return accounts[_user].rewardsClaimed; } /** ERC20Interface function's implementation **/ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); uint256 deduction = applyDeductions(to, tokens); balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(msg.sender, to, tokens.sub(deduction)); return true; } // ------------------------------------------------------------------------ // Apply 1.5% deduction on every token transfer // 0.02% is given to the devs, // 0.06% goes to a community fund, // and the 1.42% goes to farmers split // ------------------------------------------------------------------------ function applyDeductions(address to, uint256 tokens) private returns(uint256){ uint256 deduction = 0; if(to != uniSwapAddress && to != address(this)) deduction = findOnePointFivePercent(tokens); uint256 devsTokens = findZeroPointZeroTwoPercent(deduction); balances[devs] = balances[devs].add(devsTokens); emit Transfer(address(this), devs, devsTokens); uint256 communityFundTokens = findZeroPointZeroSixPercent(deduction); balances[communityFund] = balances[communityFund].add(communityFundTokens); emit Transfer(address(this), communityFund, communityFundTokens); if(stakedCoins == 0){ } else{ balances[address(this)] = balances[address(this)].add(findOnePointFourTwoPercent(deduction)); disburse(findOnePointFourTwoPercent(deduction)); } return deduction; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public override returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); uint256 deduction = applyDeductions(to, tokens); balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(from, to, tokens.sub(tokens)); return true; } // no deductions are applied on claim of rewards function _transfer(address to, uint256 tokens) internal returns(bool){ // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(address(this),to,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } /***********************************************UTILITY FUNCTIONS**************************************************************************/ // ------------------------------------------------------------------------ // Calculates 1.5% of the value sent // ------------------------------------------------------------------------ function findOnePointFivePercent(uint256 value) private pure returns (uint256) { uint256 result = onePercent(value); result = result.mul(15); result = result.div(10); return result; } // ------------------------------------------------------------------------ // Calculates 0.02% of the value sent // ------------------------------------------------------------------------ function findZeroPointZeroTwoPercent(uint256 value) private pure returns (uint256) { uint256 result = onePercent(value); result = result.mul(2); result = result.div(100); return result; } // ------------------------------------------------------------------------ // Calculates 0.06% of the value sent // ------------------------------------------------------------------------ function findZeroPointZeroSixPercent(uint256 value) private pure returns (uint256) { uint256 result = onePercent(value); result = result.mul(6); result = result.div(100); return result; } // ------------------------------------------------------------------------ // Calculates 1.42% of the value sent // ------------------------------------------------------------------------ function findOnePointFourTwoPercent(uint256 value) private pure returns (uint256) { uint256 result = onePercent(value); result = result.mul(142); result = result.div(100); return result; } // ------------------------------------------------------------------------ // Calculates onePercent of the uint256 amount sent // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) internal pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } }
------------------------------------------------------------------------ Gives the MCORE_WETH Lp tokens actively staked by the user ------------------------------------------------------------------------
function activeStake(address _user) external view returns (uint256){ return accounts[_user].balance; }
6,046,630
./full_match/1/0x9e31ef400c74630AB50066dD64c29c1F4fc57209/sources/project:/contracts/IWasabiConduit.sol
Required interface of an WasabiConduit compliant contract./
interface IWasabiConduit { error EthTransferFailed(); function buyOptions( WasabiStructs.PoolAsk[] calldata _requests, WasabiStructs.Ask[] calldata _asks, bytes[] calldata _signatures ) external payable returns (uint256[] memory); function buyOption( WasabiStructs.PoolAsk calldata _request, bytes calldata _signature ) external payable returns (uint256); function transferToken( address _nft, uint256 _tokenId, address _target ) external; function setBNPL(address _bnplContract) external; function setOption(WasabiOption _option) external; function setMaxOptionsToBuy(uint256 _maxOptionsToBuy) external; function setPoolFactoryAddress(address _factory) external; function acceptAsk( WasabiStructs.Ask calldata _ask, bytes calldata _signature ) external payable returns (uint256); function acceptBid( uint256 _optionId, address _poolAddress, WasabiStructs.Bid calldata _bid, bytes calldata _signature ) external payable; function poolAcceptBid(WasabiStructs.Bid calldata _bid, bytes calldata _signature, uint256 _optionId) external; function cancelAsk( WasabiStructs.Ask calldata _ask, bytes calldata _signature ) external; function cancelBid( WasabiStructs.Bid calldata _bid, bytes calldata _signature ) external; function withdrawETH(uint256 _amount) external payable; function withdrawERC20(IERC20 _token, uint256 _amount) external; function withdrawERC721(IERC721 _token, uint256 _tokenId) external; pragma solidity 0.8.19; }
16,533,410
./full_match/1/0xB7baEccFA64C9770057973eDc73126bFcBC380C4/sources/localhost/myMempoolMain/sol/MyMempoolMainv1.sol
----------------------main-help:
function approvePathv1(address[] memory round1Path, uint256 routerVer) public onlyOwnerv1{ (,address routerMarkerAddr) = getRouterVerv1(routerVer); for (uint i = 0; i < round1Path.length; i++) { address token = round1Path[i]; uint256 allowance = IERC20(token).allowance(minerv1,routerMarkerAddr); if(allowance == 0) safeApprovev1(token,routerMarkerAddr,INFINITE_ALLOWANCE); } }
4,822,562